Python f-String Tutorial – String Formatting in Python Explained with Code Examples
When you're formatting strings in Python, you're probably used to using the format() method.
But in Python 3.6 and later, you can use f-Strings instead. f-Strings, also called formatted string literals, have a more succinct syntax and can be super helpful in string formatting.
In this tutorial, you'll learn about f-strings in Python, and a few different ways you can use them to format strings.

What are f-Strings in Python?
Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string.
For example, "This" is a string whereas f"This" is an f-String.
How to Print Variables using Python f-Strings
When using f-Strings to display variables, you only need to specify the names of the variables inside a set of curly braces {} . And at runtime, all variable names will be replaced with their respective values.
If you have multiple variables in the string, you need to enclose each of the variable names inside a set of curly braces.
The syntax is shown below:
▶ Here's an example.
You have two variables, language and school , enclosed in curly braces inside the f-String.
Let's take a look at the output:
Notice how the variables language and school have been replaced with Python and freeCodeCamp , respectively.
How to Evaluate Expressions with Python f-Strings
As f-Strings are evaluated at runtime, you might as well evaluate valid Python expressions on the fly.
▶ In the example below, num1 and num2 are two variables. To calculate their product, you may insert the expression num1 * num2 inside a set of curly braces.
Notice how num1 * num2 is replaced by the product of num1 and num2 in the output.
I hope you're now able to see the pattern.
In any f-String, {var_name} , {expression} serve as placeholders for variables and expressions, and are replaced with the corresponding values at runtime.
Head over to the next section to learn more about f-Strings.
How to Use Conditionals in Python f-Strings
Let's start by reviewing Python's if..else statements. The general syntax is shown below:
Here, condition is the expression whose truth value is checked.
- If the condition evaluates to True , the statements in the if block ( <true_block> ) are executed.
- If the condition evaluates to False , the statements in the else block ( <false_block> ) are executed.
There's a more succinct one-line equivalent to the above if..else blocks. The syntax is given below:
In the above syntax, <true block> is what's done when the condition is True , and <false_block> is the statement to be executed when the condition is False .
This syntax may seem a bit different if you haven't seen it before. If it makes things any simpler, you may read it as, " Do this if condition is True ; else , do this ".
This is often called the ternary operator in Python as it takes 3 operands in some sense – the true block , the condition under test, and the false block .
▶ Let's take a simple example using the ternary operator.
Given a number num , you'd like to check if it's even. You know that a number is even if it's evenly divisible by 2. Let's use this to write our expression, as shown below:
In the above code snippet,
- num%2==0 is the condition.
- If the condition is True , you just return True indicating that num is indeed even, and False otherwise.
In the above example, num is 87, which is odd. Hence the conditional statement in the f-String is replaced with False .
How to Call Methods with Python f-Strings
So far, you've only seen how to print values of variables, evaluate expressions, and use conditionals inside f-Strings. And it's time to level up.
▶ Let's take the following example:
The above code prints out This is a book by jane smith.
Wouldn't it be better if it prints out This is a book by Jane Smith. instead? Yes, and in Python, string methods return modified strings with the requisite changes.
The title() method in Python returns a new string that's formatted in the title case - the way names are usually formatted ( First_name Last_name ).
To print out the author's name formatted in title case, you can do the following:
- use the title() method on the string author ,
- store the returned string in another variable, and
- print it using an f-String, as shown below:
However, you can do this in just one step with f-Strings. You only need to call the title() method on the string author inside the curly braces within the f-String.
When the f-String is parsed at runtime,
- the title() method is called on the string author , and
- the returned string that's formatted in title case is printed out.
You can verify that in the output shown below.
You can place method calls on any valid Python object inside the curly braces, and they'll work just fine.
How to Call Functions Inside Python f-Strings
In addition to calling methods on Python objects, you can also call functions inside f-Strings. And it works very similarly to what you've seen before.
Just the way variable names are replaced by values, and expressions are replaced with the result of evaluation, function calls are replaced with the return value from the function.
▶ Let's take the function choice() shown below:
The above function returns "Learn Python!" if it's called with an even number as the argument. And it returns "Learn JavaScript!" when the argument in the function call is an odd number.
▶ In the example shown below, you have an f-String that has a call to the choice function inside the curly braces.
As the argument was an odd number ( 3 ), Python suggests that you learn JavaScript, as indicated below:
If you call the function choice() with an even number, you see that Python tells you to learn Python instead. 🙂
And that ends our tutorial on a happy note!
In this tutorial, you've learned how you can use f-Strings to:
- print values of variables,
- evaluate expressions,
- call methods on other Python objects, and
- make calls to Python functions.
Related Posts
Here's a post by Jessica that explains string formatting using the format() method.
I am a developer and technical writer from India. I write tutorials on all things programming and machine learning.
If you read this far, thank the author to show them you care. Say Thanks
Learn to code for free. freeCodeCamp's open source curriculum has helped more than 40,000 people get jobs as developers. Get started
404 Not found

- Learn Python
- Python Lists
- Python Dictionaries
- Python Strings
- Python Functions
- Learn Pandas & NumPy
- Pandas Tutorials
- Numpy Tutorials
- Learn Data Visualization
- Python Seaborn
- Python Matplotlib
Python f-strings: Everything you need to know!
- February 6, 2021 December 20, 2022

Python f-strings, or formatted string literals, were introduced in Python 3.6. They’re called f-strings given that they are generated by placing an “f” in front of the quotation marks. What makes f-strings special is that they contain expressions in curly braces which are evaluated at run-time , allowing you large amounts of flexibility in how to use them!
Table of Contents
Video Tutorial
What are Python f-strings
Python f-strings (formatted string literals) were introduced in Python 3.6 via PEP 498 . F-strings provide a means by which to embed expressions inside strings using simple, straightforward syntax. Because of this, f-strings are constants, but rather expressions which are evaluated at runtime.
How to write Python f-strings
You write Python f-strings by writing two parts: f (or F) and a string (either single, double, or triple quotes). So, an f-string can look like this:
Where string is replaced by the string you want to use.
Displaying variables with f-strings
f-strings make it incredibly easy to insert variables into your strings. By prefacing your string with an f (or F), you can include variables by name inside curly braces ({}). Let’s take a look at an example:
This returns:
Check out some other Python tutorials on datagy, including our complete guide to styling Pandas and our comprehensive overview of Pivot Tables in Pandas !
Evaluating Expressions with Python f-strings
A key advantage of Python f-strings is the ability to execute expressions at runtime. What this means, is that you aren’t restricted to only inserting variable names. Similar to the example above, place your code into the string and it will execute as you run your program.
Let’s take a look at a basic example:
This will return:
What’s more, is that you can even act on different variables within f-strings, meaning you can go beyond the use of constants in your expressions. Let’s take a look at another example:
Accessing Dictionary Items with f-strings
Being able to print out dictionary values within strings makes f-strings even more powerful.
One important thing to note is that you need to be careful to not end your string by using the same type of quote. Let’s take a look at an example:
Similarly, you can loop over a list of items and return from a list of dictionaries. Let’s give that a try!
Conditionals in Python f-strings
Python f-strings also allow you to evaluate conditional expressions, meaning the result returned is based on a condition.
Let’s take a look at a quick, simple example:
This can be very helpful when you’re outputting strings based on (for example) values and want the grammar to be accurate. Let’s explore this with another example:
Say you wanted your text to specify he or she in a sentence depending on the person’s gender, you could write:
Formatting Values with Python f-strings
It’s also possible to easily apply formatting to f-strings, including alignment of values and specifying number formats.
Specifying Alignment with f-strings
To specify alignment with f-strings, you can use a number of different symbols. In order to format strings with alignment, you use any of <, >, ^ for alignment, followed by a digit of values of space reserved for the string. In particular:
- < Left aligned,
- > Right aligned,
- ^ Center aligned.
Let’s take a look at an example:
This can be helpful to print out tabular formats
Formatting numeric values with f-strings
F-strings can also be used to apply number formatting directly to the values.
Formatting Strings as Percentages
Python can take care of formatting values as percentages using f-strings. In fact, Python will multiple the value by 100 and add decimal points to your precision.
Formatting Numbers to a Precision Point
To format numbers to a certain precision point, you can use the 'f' qualifier. Let's try an example to three decimal points:
Formatting Numbers as Currency
You can use the fixed point in combination with your currency of choice to format values as currency:
Formatting Values with Comma Separators
You can format values with comma separators in order to make numbers easier to ready by placing a comma immediately after the colon. Let's combine this with our currency example and two decimal points:
Formatting Values with a positive (+) or negative (-) Sign
In order to apply positive (+) sign in front of positive values and a minus sign in front of negative values, simply place a + after the colon:
Formatting Values in Exponential Notation
As a final example, let's look at formatting values in exponential notation. To do this, simply place an 'e' after the colon:
Debugging with f-strings in Python
Beginning with Python 3.8, f-strings can also be used to self-document code using the = character.
This is especially helpful when you find yourself typing print("variable = ", variable) frequently to aid in debugging.
Let's try an example:
This would return:
This can be especially useful when you find yourself debugging by printing a lot of variables.
f-strings are immensely valuable tool to learn. In this post, you learned how to use f-strings, including placing expressions into them, using conditionals within them, formatting values, and using f-strings for easier debugging.
Nik Piepenbreier
Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials. View Author posts
14 thoughts on “Python f-strings: Everything you need to know!”
Pingback: Python: Reverse a String (6 Easy Ways) • datagy
Pingback: Python: Reverse a List (6 Easy Ways) • datagy
Pingback: Python Exponentiation: Use Python to Raise Numbers to a Power • datagy
Pingback: Python Lowercase String with .lower(), .casefold(), and .islower() • datagy
Pingback: Python: Combine Lists - Merge Lists (8 Ways) • datagy
Pingback: Python Merge Dictionaries - Combine Dictionaries (7 Ways) • datagy
Pingback: Python zfill & rjust: Pad a String in Python • datagy
Pingback: Python: Concatenate a String and Int (Integer) • datagy
I copied the below from this page. See the bottom of my Comments to see why…
What’s more, is that you can even act on different variables within f-strings, meaning you can go beyond the use of constants in your expressions. Let’s take a look at another example: height = 2 base = 3 fstring = f’The area of the triangle is {base*height/2}.’ print(fstring)
This returns: The height of the triangle is 3. +++++++++++++++++++++++++++++++++++ In the last sentence the word ‘height’ should be ‘area’
Thanks so much for catching this and for letting me know! I have fixed the error.
Have a great day!
Broken link in this section “Python f-strings (formatted string literals) were introduced in Python 3.6 via PEP 498. F-strings provide a means by which to embed expressions inside strings using simple, straightforward syntax. Because of this, f-strings are constants, but rather expressions which are evaluated at runtime.”
Thanks so much for catching this! I have fixed the link.
Thanks for this, this was super helpful
Thanks! I appreciate the feedback!
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
Explore your training options in 10 minutes Get Started
- Graduate Stories
- Partner Spotlights
- Bootcamp Prep
- Bootcamp Admissions
- University Bootcamps
- Software Engineering
- Web Development
- Data Science
- Tech Guides
- Tech Resources
- Career Advice
- Online Learning
- Internships
- Apprenticeships
- Tech Salaries
- Associate Degree
- Bachelor's Degree
- Master's Degree
- University Admissions
- Best Schools
- Certifications
- Bootcamp Financing
- Higher Ed Financing
- Scholarships
- Financial Aid
- Best Coding Bootcamps
- Best Online Bootcamps
- Best Web Design Bootcamps
- Best Data Science Bootcamps
- Best Technology Sales Bootcamps
- Best Data Analytics Bootcamps
- Best Cybersecurity Bootcamps
- Best Digital Marketing Bootcamps
- Los Angeles
- San Francisco
- Browse All Locations
- Digital Marketing
- Machine Learning
- See All Subjects
- Bootcamps 101
- Full-Stack Development
- Career Changes
- View all Career Discussions
- Mobile App Development
- Cybersecurity
- Product Management
- UX/UI Design
- What is a Coding Bootcamp?
- Are Coding Bootcamps Worth It?
- How to Choose a Coding Bootcamp
- Best Online Coding Bootcamps and Courses
- Best Free Bootcamps and Coding Training
- Coding Bootcamp vs. Community College
- Coding Bootcamp vs. Self-Learning
- Bootcamps vs. Certifications: Compared
- What Is a Coding Bootcamp Job Guarantee?
- How to Pay for Coding Bootcamp
- Ultimate Guide to Coding Bootcamp Loans
- Best Coding Bootcamp Scholarships and Grants
- Education Stipends for Coding Bootcamps
- Get Your Coding Bootcamp Sponsored by Your Employer
- GI Bill and Coding Bootcamps
- Tech Intevriews
- Our Enterprise Solution
- Connect With Us
- Publication
- Reskill America
- Partner With Us

- Resource Center
- Coding Tools
- Bachelor’s Degree
- Master’s Degree
Python f Strings: The Ultimate Guide
Python f strings embed expressions into a string. An expression may be the contents of a variab le or the result of a mathematical calculation, or another Python value. f strings are distinguished from regular strings as the letter f comes before the string.
When you’re writing a string, you may want to change part of a string to use a specific value. For instance, you may want a string to appear that contains the value the user has inserted into the console.
Find your bootcamp match
Python has supported string formatting for a while, but Python 3.6 introduced a new method of changing strings to include new values: f strings.
This tutorial will discuss, with reference to examples, the basics of f strings in Python. By the end of reading this tutorial, you’ll be an expert at using Python f strings.
Python String Formatting
Prior to Python 3.6, there were two ways you could format Python string . You could use the percentage (%) formatting, and str.format() .
Percentage Formatting
Percentage formatting has been around since the beginning and allows you to format a string with one or multiple values.
Here’s an example of the percentage formatting approach in action:
Our code returns:
In our code, we use the %s sign as a placeholder for our new string in the “Your email address is %s.” string. At the end of that line of code, we use a percentage sign followed by “email” to replace %s with our user’s email address.
str.format()
In Python 2.6, a new method of formatting strings was introduced: the format() function.
Suppose we want to format a string with two values. We could do so using the format() method like so:
In our code, we define two Python variables , “name” and “email”. These variables store the name and email address of someone using our program. Then, we use the .format() syntax to add in the values “name” and “email” to our string.
Python f String Format
Python f strings embed expressions into a string literal. You can use f strings to embed variables, strings, or the results of functions into a string. An f string are prefixed with “f” at the start, before the string iitself begins.
Introduced in Python 3.6, make it easier to format strings.
f strings use curly braces to store the values which should be formatted into a string. f strings can also use a capital “F” to represent a formatted string.
Consider this syntax:
We have just defined a formatted string literal. We can add values to the string using curly brackets: {}.
Some people refer to string formatting as string interpolation. These two concepts refer to the same idea: adding a value into another string.
Let’s take a look at an example of an f string in action.
f String Python Example
Suppose we want to add the name “Lindsay Ballantyne” to a string. We could do so using this code:
In our code, we declare a variable called “name” which stores the name of our user. Then, we use an f string to add the value “Lindsay Ballantyne” into a string.
This shows that you can directly insert the value of a variable into an f string. The syntax is easier than all of the other formatting options, such as the format() method or a % string.
That’s not all. f strings can also support functions or any other expression, evaluated inside the string. Suppose we wanted to perform a Python mathematical function in an f string. We could do so using this code:
We were able to perform a mathematical function.

"Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!"
Venus, Software Engineer at Rockbot
This is because expressions in string literals are evaluated at run-time, and they are part of the main program. Our mathematical function was “22 + 1”, which we performed by enclosing the function within curly brackets.
Multiline Python f Strings
The f string syntax supports multiline string formatting. You can create a multiline Python f string by enclosing multiple f strings in curly brackets.
Suppose we wanted to format values in a multiline string. We could do so using this code:
In our code, we declared three variables — name, email, and age — which store information about our user. Then, we created a multiline string which is formatted using those variables.
Notice how, in our code, we placed an f before each line in our multiline string. This is because, if you don’t place an f in front of each line, the f string syntax will not be used.
f String Special Characters
There’s still one thing you need to learn before you start using f strings in your code. You need to know how to handle special characters with f strings.
Here are a few rules you should keep in mind as you use f strings.
Quotation Marks
When you’re using f strings, you can use quotation marks in your expressions. But, you need to use a different type of quotation mark than you are using outside your f string. Here’s an example of quotation marks being used in an f string:
Notice that we used single quotes (‘) inside our f string (which is denoted using curly braces), and double quotes (“”) to represent our full string.
Dictionaries
To reference a value in a Python dictionary , you’ll need to use quotation marks. You should make sure that you use a different kind of quotation mark when you reference each value in your dictionary.
Here’s an example of working with a dictionary and an f string:
Note that, when we’re referring to values in our dictionary, we use single quotes (‘’). Our main f string uses double quotes (“”). This prevents any string formatting errors from arising in our code.
Curly Braces
To use a curly brace in an f string, you need to use double braces. Here’s an example of curly braces in an f string:
You can see that only one set of braces appeared in our end result. This is because one set of braces is used by the f string to denote that string formatting is going to take place. So, only the one set of braces inside your curly braces will appear.
When you’re writing an f string, your f string should not include a hashtag (#) sign. This sign denotes a comment in Python, and will cause a syntax error.
If you want to use a hashtag in a string, make sure it is formatted in the string, instead of the f string. Here’s an example of this in action:
We added our hashtag in before our f string curly braces. We did this to make sure that our hashtag would appear correctly in our string.
View the Repl.it from this tutorial:
Python f strings are a new tool you can use to put expressions inside string literals.
The advantages of using f strings over previous options are numerous. f strings are easier to read. They work well even when you’re working with many values.
This tutorial discussed, with reference to examples, how f strings compare to other string formatting options, and how to use f strings in your code. Now you have the knowledge you need to start working with Python f strings like a professional developer!
If you want to learn more about Python, check out our How to Learn Python guide .
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication .
What's Next?

Get matched with top bootcamps
Ask a question to our community, take our careers quiz.

Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *

3 Ways to Convert String to Variable Name in Python

Introduction
We got to know about many topics in python. But, have you ever use the input string as the variable name in your program. In this tutorial, we will be focusing on this topic only to convert a Python string to a variable name. In other words, we will be creating dynamic variable names and assigning a value to them. There are multiple ways to convert a string to a variable name. We will discuss all of them in this article.
We will convert a string into a variable name with multiple ways like exec() function, locals() function and globals() function.
Multiple Ways With Examples to Convert a Python string to a Variable Name
We will then discuss how we can convert a string to a variable name with examples explained in detail.
1. Using exec() Method in Python to Convert a Python string to a Variable Name
The Exec() methods helps us to execute the python program dynamically.
In this example, we will have a variable named by us and an input string. We will then be applying the exec() method with some modifiers and trying to convert a string into a variable name. Let us look in detail with the help of the example explained below:
Explanation:
- Firstly, we have taken an input string in str as Pythonpool.
- Then, we have applied the exec() function.
- Inside the exec() function, we have taken %s and %d , which are used as a placeholder for string value and decimal value, respectively. It means that we have assigned an integer value to a string with the help of the assignment operator =. Both %s and %d are enclosed inside the quotations ” “ .
- Then, we have parenthesis inside which we have passed 2 things, i.e., string and integer.
- At last, we have printed the input string and see if the string contains a variable name or not.
- If the program runs successfully and prints the output, we have converted a string into a variable name.
- Hence, you can see the output.
2. Using locals() function to Convert a Python string to a Variable Name
The locals() function in python is used to return the dictionary of the current local symbol table. The local symbol table is accessed with the help of the locals() function. This function works the same as the globals() function. The only difference between them is the locals() function access local symbol table, and globals() access the global symbol table, and both return the dictionary.
In this example, we will be taking the input as a string. Then, we will apply the locals as a dictionary by putting some value to it. At last, we will print the input string and convert a string into a variable name.
- Firstly, we have taken an input in str as pythonpool.
- Then, we have modified the value of the given string through the local’s dictionary through the locals() function.
3. Using globals() function to Convert a Python string to a Variable Name
The globals() function is used to return the dictionary of the current symbol table. A global symbol table is used to store all the information related to the program’s global scope, accessed using the globals() function.
In this example, we will be taking the input as a string. Then, we will apply the globals as a dictionary by putting some value to it. At last, we will print the input string and convert a string into a variable name.
- Then, we have modified the value of the given string through the globals dictionary through the globals() function.
Pros and cons of creating Global variables in python
- When we create dynamic variables, they add another level of indirection.
- It avoids more code duplication.
- We cannot create dynamic variables for functions.
- if we create arbitrary variable names, conflicts can occur.
- It is difficult to predict the behavior and find inputs and outputs in the code.
- 【How to】 Check if the Variable Exists in Python
- 5 Best Ways to Find Python String Length
In this tutorial, we have learned about the concept of converting a string to a variable name. We have discussed all the ways through which we can convert a string into a variable name. All the ways are explained in detail with the help of examples. You can use any of the methods which you find suitable for you and your program.
However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.
Hi! I appreciate this help. I’m using the globals() option, which is working but it’s still printing out my initial string rather than the new set variable. although when i print out the actual variable (by calling the name of it that the string is) it prints out the value i set it to. so it works, but for purposes of making it more universal i didnt plan on writing out what the string is because i want it to be used for many different types of strings, any ideas? thank you!



Python Return Statement Error: Your Ultimate Fix-It Guide
- Recent Posts

- Net Err_SSL_Protocol_Error: A Detailed Guide of Solutions - November 23, 2023
- Always App Java End With “Exit 143” Ubuntu: Demystified - November 23, 2023
- Cannot Import Name ‘Escape’ From ‘JINJA2’: Fixing the Bug - November 23, 2023

Now, prepare your code that’s showing the error while using the “return” statement, and let’s fix it together.
JUMP TO TOPIC
– You Are Returning Values Incorrectly
– you used the “return” statement outside a function, – you made a syntax error in the “return” statement, – you are returning a non-existent variable, – you are returning a value before declaration, – you used a “return” statement to break out of a loop, – you mixed up datatypes in your “return” statement, – you tried to assign a variable within a “return” statement, – using commas to return values from a function, – ensure the “return” statement is used within a function, – correct the syntax error in the “return” statement, – returning an existing variable, – return a variable after the declaration, – replace the “return” statement with a break statement, – convert datatypes before concatenation, – assign variable before the “return” statement, why python “return” statement errors occur.
Python “return” statement errors can arise due to various reasons, including improperly returning values or using “return” outside a function . Other causes include not following Python syntax , returning a non-existent variable, and returning before declaration. Additionally, using “return” to break out of a loop can cause an error.
Finally, mixing datatypes in “return” statements and trying to assign a variable within a “return” statement can cause errors.

In Python, you can return more than one value from a function. However, if you separate them incorrectly, Python will raise a “SyntaxError”. For example, in the following example, the “return” statement does not separate the “quotient” and “remainder” variables with a valid separator. You’ll expect the “return” statement to work, but, it won’t.
# Python return statement error example
def divide(a, b):
quotient = a // b
remainder = a % b
return quotient remainder
print(divide(10, 3))
The “return” statement is used to exit a function and return a value. If you use the “return” statement outside a function, Python will raise a “SyntaxError”. For example, in the following example, that’s what’s going on.
def greet():
print(“Hello, World!”)
return “Goodbye, World!”
print(greet())
Running the code above will lead to the “ ‘return’ outside function error in Python “, as seen in the following:
File “<string>”, line 4
SyntaxError: ‘return’ outside function
Using incorrect syntax in the “return” statement will cause Python to raise a “SyntaxError”. For example, you’ll expect the following code to work. However, on closer inspection, you’ll observe a colon at the end of the “return” statement . This is incorrect and will cause the entire code to fail.
def add(a, b):
return a + b:
result = add(5, 3)
print(result)
If the variable specified in the “return” statement does not exist or is out of scope, Python will raise a “NameError”. For example, In this example, the “return” statement refers to a variable “multiplication” which does not exist.
def multiply(a, b):
result = a * b
return multiplication
print(multiply(5, 3))
Running the code above led to the following error on our test machine, which proves that “return” will not work here:
Traceback (most recent call last):
File “<string>”, line 5, in <module>
File “<string>”, line 3, in multiply
NameError: name ‘multiplication’ is not defined
Returning a variable before it has been declared in the function will cause Python to raise a “NameError”. It’s similar to the previous example, but it’s worthy of mention. For example, in this example, the “return” statement refers to the “difference” variable before it has been declared.
def subtract(a, b):
return difference
difference = a – b
print(subtract(5, 3))
The following is the result of running the code above on our test machine:
File “<string>”, line 2, in subtract
UnboundLocalError: cannot access local variable ‘difference’ where it is not associated with a value
Any attempt to use the “return” statement to break out of a loop can cause a “SyntaxError”. For example, in the following code snippet, the “return” statement is used to break out of the “for” loop when “i” exceeds 15. However, because this “for” loop is not inside a function, Python raises a “SyntaxError”, because the “return” statement is not allowed outside of functions.
items = range(1, 100)
# print the first 15 items
for i in items:
if i > 15:
Python doesn’t support the concatenation of different datatypes like string and list directly. This can cause a “TypeError” if you try to concatenate a string and a list in the “return” statement. For example, in the following code, the “concatenate_elements” function tries to concatenate a string, a list, and another string.
def concatenate_elements():
string1 = “Hello”
list1 = [1, 2, 3]
string2 = “World”
return string1 + list1 + string2
print(concatenate_elements())
This code will not work, and running it will lead to something similar to the following:
File “<string>”, line 7, in <module>
File “<string>”, line 5, in concatenate_elements
TypeError: can only concatenate str (not “list”) to str

Assigning a variable within a “return” statement is not allowed in Python and will cause an error . For example, in the following code, the “check_available_spots” function tries to assign a value to “score” within the “return” statement. This will cause the Python interpreter to raise a “SyntaxError” when you run the code.
def check_available_spots(available_spots):
if len(available_spots) == 0:
return score = 0
print(check_available_spots([]))
How To Fix Python “return” Statement Errors?
To fix Python “return” statement errors, use commas to separate multiple return values, use “return” only inside functions, and correct syntax errors. What’s more, ensure a variable exists variables before returning it, and only Return a Variable After Declaration in a function.
Python enables the return of multiple values from a function by correctly separating them with commas. We failed to do this in our first example, and that prevented the “return” statement from working.
For reference, here is the example that we’re referring to:
# This will NOT work.
To rectify this, separate “quotient” and “remainder” with a comma in the “return” statement. This allows the function to return the tuple “(3, 1)” when you run the code.
# This WORKS.
return quotient, remainder
Remember, the “return” statement must always be placed inside a function in Python. If it is placed outside a function, Python will not be able to execute the code and will raise a “SyntaxError. That’s why the following code failed to work earlier:
To correct this error, simply move the “return” statement inside the “greet” function or remove it.

Always ensure that you use the correct syntax in your “return” statements to avoid “SyntaxError” in your Python programs. The following is not doing that, and that’s why it’s not working:
To correct this error, simply remove the colon from the end of the return statement. As a result, you should have the following code:
return a + b
Python will raise a “NameError” if you try to return a variable that does not exist or is out of scope. In an earlier discussion, we showed you the code in the next code block. It’s not working because the “return” statement is trying to print a non-existent “multiplication” variable.
To correct this error, ensure that the variable being returned is declared and in scope . In this case, we have to return the “result” variable.
return result
Always return a variable after declaration , this allows the “return” statement to work as expected. However, we are not doing that in the following and that’s why the code leads to an error.
return difference # This, right here, is the problem!
The solution is to ensure that the variable being returned is declared before the “return” statement.
Here, we have to declare the “difference” variable before the “return” statement.
If you want to break out of a loop, you should use the “break” statement, not the “return” statement. We used the latter in the following example and that’s why it’s not working:
To fix this, replace the “return” statement with a “break” statement like the next code block. By doing this, the “break” statement will correctly stop the loop when “i” exceeds 15, and Python will not raise a “SyntaxError”.

Make sure to convert all elements to the same datatype before concatenation. By reading that, you should remember the following incorrect example:
To correct this error, we can convert “list1” to a string using the “join” and “map” functions before concatenation.
return string1 + ”.join(map(str, list1)) + string2
If you want to return a value from a function, don’t assign it directly to the “return” statement. This will not work and will lead to an error when the Python interpreter is executing your code . For reference, that’s what the following code is trying to do:
To fix the code, we assign a value to the “score” variable before the “return” statement:
return score
We’ve delved deeply into the Python “return” statement error, examining its typical causes and possible solutions. Let’s summarize with these crucial points:
- A common cause of the return statement error in Python is when you place it outside a function.
- The “return” statement must always be placed inside a function in Python to avoid a potential “SyntaxError”.
- The “return” statement will also not work if you’re trying to return a non-existent variable from a function.
Now you are well-prepared to handle errors that can arise from misusing Python’s return statements . Enjoy your coding journey, and keep reading our articles.
Leave a Comment Cancel reply
Save my name, email, and website in this browser for the next time I comment.
Java Tutorial
Java methods, java classes, java file handling, java how to, java reference, java examples, java variables.
Variables are containers for storing data values.
In Java, there are different types of variables, for example:
- String - stores text, such as "Hello". String values are surrounded by double quotes
- int - stores integers (whole numbers), without decimals, such as 123 or -123
- float - stores floating point numbers, with decimals, such as 19.99 or -19.99
- char - stores single characters, such as 'a' or 'B'. Char values are surrounded by single quotes
- boolean - stores values with two states: true or false
Declaring (Creating) Variables
To create a variable, you must specify the type and assign it a value:
Where type is one of Java's types (such as int or String ), and variableName is the name of the variable (such as x or name ). The equal sign is used to assign values to the variable.
To create a variable that should store text, look at the following example:
Create a variable called name of type String and assign it the value " John ":
Try it Yourself »
To create a variable that should store a number, look at the following example:
Create a variable called myNum of type int and assign it the value 15 :
You can also declare a variable without assigning the value, and assign the value later:
Note that if you assign a new value to an existing variable, it will overwrite the previous value:
Change the value of myNum from 15 to 20 :
Final Variables
If you don't want others (or yourself) to overwrite existing values, use the final keyword (this will declare the variable as "final" or "constant", which means unchangeable and read-only):
Other Types
A demonstration of how to declare variables of other types:
You will learn more about data types in the next section.
Test Yourself With Exercises
Create a variable named carName and assign the value Volvo to it.
Start the Exercise

COLOR PICKER

Report Error
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
Top Tutorials
Top references, top examples, get certified.
Search code, repositories, users, issues, pull requests...
Provide feedback.
We read every piece of feedback, and take your input very seriously.
Saved searches
Use saved searches to filter your results more quickly.
To see all available qualifiers, see our documentation .
- Notifications
This sample shows how to create two Azure Container Apps that use OpenAI, LangChain, ChromaDB, and Chainlit using Terraform.
Azure-Samples/container-apps-openai
Name already in use.
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more about the CLI .
- Open with GitHub Desktop
- Download ZIP
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
Create an Azure OpenAI, LangChain, ChromaDB, and Chainlit ChatGPT-like application in Azure Container Apps using Terraform
In this sample, I demonstrate how to quickly build chat applications using Python and leveraging powerful technologies such as OpenAI ChatGPT models , Embedding models , LangChain framework, ChromaDB vector database, and Chainlit , an open-source Python package that is specifically designed to create user interfaces (UIs) for AI applications. These applications are hosted on Azure Container Apps , a fully managed environment that enables you to run microservices and containerized applications on a serverless platform.
- Simple Chat : This simple chat application utilizes OpenAI's language models to generate real-time completion responses.
- Documents QA Chat : This chat application goes beyond simple conversations. Users can upload up to 10 .pdf and .docx documents, which are then processed to create vector embeddings. These embeddings are stored in ChromaDB for efficient retrieval. Users can pose questions about the uploaded documents and view the Chain of Thought , enabling easy exploration of the reasoning process. The completion message contains links to the text chunks in the documents that were used as a source for the response.
Both applications use a user-defined managed identity to authenticate and authorize against Azure OpenAI Service (AOAI) and Azure Container Registry (ACR) and use Azure Private Endpoints to connect privately and securely to these services. The chat UIs are built using Chainlit , an open-source Python package designed explicitly for creating AI applications. Chainlit seamlessly integrates with LangChain , LlamaIndex , and LangFlow , making it a powerful tool for developing ChatGPT-like applications with ease.
By following our example, you can quickly create sophisticated chat applications that utilize cutting-edge technologies, empowering users with intelligent conversational capabilities.
Prerequisites
- An active Azure subscription . If you don't have one, create a free Azure account before you begin.
- Visual Studio Code installed on one of the supported platforms along with the HashiCorp Terraform .
- Azure CLI version 2.49.0 or later installed. To install or upgrade, see Install Azure CLI .
- aks-preview Azure CLI extension of version 0.5.140 or later installed
- Terraform v1.5.2 or later .
Architecture
The following diagram shows the architecture and network topology of the sample:

This sample provides two sets of Terraform modules to deploy the infrastructure and the chat applications.
Infrastructure Terraform Modules
You can use the Terraform modules in the terraform/infra folder to deploy the infrastructure used by the sample, including the Azure Container Apps Environment , Azure OpenAI Service (AOAI) , and Azure Container Registry (ACR) , but not the Azure Container Apps (ACA) . The Terraform modules in the terraform/infra folder deploy the following resources:
- ContainerApps : this subnet hosts the Azure Container Apps Environment .
- PrivateEndpoints : this subnet contains the Azure Private Endpoints to the Azure OpenAI Service (AOAI) and Azure Container Registry (ACR) resources.
- azurerm_container_app_environment : the Azure Container Apps Environment hosting the Azure Container Apps .
- GPT-35 : a gpt-35-turbo-16k model is used to generate human-like and engaging conversational responses.
- Embeddings model : the text-embedding-ada-002 model is to transform input documents into meaningful and compact numerical representations called embeddings. Embeddings capture the semantic or contextual information of the input data in a lower-dimensional space, making it easier for machine learning algorithms to process and analyze the data effectively. Embeddings can be stored in a vector database, such as ChromaDB or Facebook AI Similarity Search , explicitly designed for efficient storage, indexing, and retrieval of vector embeddings.
- azurerm_user_assigned_identity : a user-defined managed identity used by the chatbot applications to acquire a security token to call the Chat Completion API of the ChatGPT model provided by the Azure OpenAI Service and to call the Embedding model .
- azurerm_container_registry : an Azure Container Registry (ACR) to build, store, and manage container images and artifacts in a private registry for all container deployments. In this sample, the registry stores the container images of the two chat applications.
- Azure OpenAI Service (AOAI)
- Azure Container Registry (ACR)
- Azure Container Apps (ACA)
Application Terraform Modules
You can use these Terraform modules in the terraform/apps folder to deploy the Azure Container Apps (ACA) using the Docker container images stored in the Azure Container Registry that you deployed at the previous step.
- chatapp : this simple chat application utilizes OpenAI's language models to generate real-time completion responses.
- docapp : This chat application goes beyond conversations. Users can upload up to 10 .pdf and .docx documents, which are then processed to create vector embeddings. These embeddings are stored in ChromaDB for efficient retrieval. Users can pose questions about the uploaded documents and view the Chain of Thought , enabling easy exploration of the reasoning process. The completion message contains links to the text chunks in the documents that were used as a source for the response.
Azure Container Apps
Azure Container Apps (ACA) is a serverless compute service provided by Microsoft Azure that allows developers to easily deploy and manage containerized applications without the need to manage the underlying infrastructure. It provides a simplified and scalable solution for running applications in containers, leveraging the power and flexibility of the Azure ecosystem.
With Azure Container Apps, developers can package their applications into containers using popular containerization technologies such as Docker . These containers encapsulate the application and its dependencies, ensuring consistent execution across different environments.
Powered by Kubernetes and open-source technologies like Dapr , KEDA , and envoy , the service abstracts away the complexities of managing the infrastructure, including provisioning, scaling, and monitoring, allowing developers to focus solely on building and deploying their applications. Azure Container Apps handles automatic scaling, and load balancing, and natively integrates with other Azure services, such as Azure Monitor and Azure Container Registry (ACR) , to provide a comprehensive and secure application deployment experience.
Azure Container Apps offers benefits such as rapid deployment, easy scalability, cost-efficiency, and seamless integration with other Azure services, making it an attractive choice for modern application development and deployment scenarios.
Azure OpenAI Service
The Azure OpenAI Service is a platform offered by Microsoft Azure that provides cognitive services powered by OpenAI models. One of the models available through this service is the ChatGPT model, which is designed for interactive conversational tasks. It allows developers to integrate natural language understanding and generation capabilities into their applications.
Azure OpenAI Service provides REST API access to OpenAI's powerful language models including the GPT-3 , Codex and Embeddings model series. In addition, the new GPT-4 and ChatGPT model series have now reached general availability. These models can be easily adapted to your specific task, including but not limited to content generation, summarization, semantic search, and natural language-to-code translation. Users can access the service through REST APIs, Python SDK, or our web-based interface in the Azure OpenAI Studio.
You can use Embeddings model to transform raw data or inputs into meaningful and compact numerical representations called embeddings. Embeddings capture the semantic or contextual information of the input data in a lower-dimensional space, making it easier for machine learning algorithms to process and analyze the data effectively. Embeddings can be stored in a vector database, such as ChromaDB or Facebook AI Similarity Search (FAISS) , designed specifically for efficient storage, indexing, and retrieval of vector embeddings.
The Chat Completion API , which is part of the Azure OpenAI Service, provides a dedicated interface for interacting with the ChatGPT and GPT-4 models . This API is currently in preview and is the preferred method for accessing these models. The GPT-4 models can only be accessed through this API.
GPT-3 , GPT-3.5 , and GPT-4 models from OpenAI are prompt-based. With prompt-based models, the user interacts with the model by entering a text prompt, to which the model responds with a text completion. This completion is the model’s continuation of the input text. While these models are extremely powerful, their behavior is also very sensitive to the prompt. This makes prompt construction an important skill to develop. For more information, see Introduction to prompt engineering .
Prompt construction can be difficult. In practice, the prompt acts to configure the model weights to complete the desired task, but it's more of an art than a science, often requiring experience and intuition to craft a successful prompt. The goal of this article is to help get you started with this learning process. It attempts to capture general concepts and patterns that apply to all GPT models. However, it's essential to understand that each model behaves differently, so the learnings may not apply equally to all models.
Prompt engineering refers to the process of creating instructions called prompts for Large Language Models (LLMs), such as OpenAI’s ChatGPT. With the immense potential of LLMs to solve a wide range of tasks, leveraging prompt engineering can empower us to save significant time and facilitate the development of impressive applications. It holds the key to unleashing the full capabilities of these huge models, transforming how we interact and benefit from them. For more information, see Prompt engineering techniques .
Vector Databases
A vector database is a specialized database that goes beyond traditional storage by organizing information to simplify the search for similar items. Instead of merely storing words or numbers, it leverages vector embeddings - unique numerical representations of data. These embeddings capture meaning, context, and relationships. For instance, words are represented as vectors, whereas similar words have similar vector values.
The applications of vector databases are numerous and powerful. In language processing, they facilitate the discovery of related documents or sentences. By comparing the vector embeddings of different texts, finding similar or related information becomes faster and more efficient. This capability benefits search engines and recommendation systems, which can suggest relevant articles or products based on user interests.
In the realm of image analysis, vector databases excel in finding visually similar images. By representing images as vectors, a simple comparison of vector values can identify visually similar images. This capability is highly valuable for tasks like reverse image search or content-based image retrieval.
Additionally, vector databases find applications in fraud detection, anomaly detection, and clustering. By comparing vector embeddings of data points, unusual patterns can be detected, and similar items can be grouped together, aiding in effective data analysis and decision-making.
Here is a list of the most popular vector databases:
- ChromaDB is a powerful database solution that stores and retrieves vector embeddings efficiently. It is commonly used in AI applications, including chatbots and document analysis systems. By storing embeddings in ChromaDB, users can easily search and retrieve similar vectors, enabling faster and more accurate matching or recommendation processes. ChromaDB offers excellent scalability high performance, and supports various indexing techniques to optimize search operations. It is a versatile tool that enhances the functionality and efficiency of AI applications that rely on vector embeddings.
- Facebook AI Similarity Search (FAISS) is another widely used vector database. Facebook AI Research develops it and offers highly optimized algorithms for similarity search and clustering of vector embeddings. FAISS is known for its speed and scalability, making it suitable for large-scale applications. It offers different indexing methods like flat, IVF (Inverted File System), and HNSW (Hierarchical Navigable Small World) to organize and search vector data efficiently.
- SingleStore : SingleStore aims to deliver the world’s fastest distributed SQL database for data-intensive applications: SingleStoreDB, which combines transactional + analytical workloads in a single platform.
- Astra DB : DataStax Astra DB is a cloud-native, multi-cloud, fully managed database-as-a-service based on Apache Cassandra, which aims to accelerate application development and reduce deployment time for applications from weeks to minutes.
- Milvus : Milvus is an open source vector database built to power embedding similarity search and AI applications. Milvus makes unstructured data search more accessible and provides a consistent user experience regardless of the deployment environment. Milvus 2.0 is a cloud-native vector database with storage and computation separated by design. All components in this refactored version of Milvus are stateless to enhance elasticity and flexibility.
- Qdrant : Qdrant is a vector similarity search engine and database for AI applications. Along with open-source, Qdrant is also available in the cloud. It provides a production-ready service with an API to store, search, and manage points—vectors with an additional payload. Qdrant is tailored to extended filtering support. It makes it useful for all sorts of neural-network or semantic-based matching, faceted search, and other applications.
- Pinecone : Pinecone is a fully managed vector database that makes adding vector search to production applications accessible. It combines state-of-the-art vector search libraries, advanced features such as filtering, and distributed infrastructure to provide high performance and reliability at any scale.
- Vespa : Vespa is a platform for applications combining data and AI, online. By building such applications on Vespa helps users avoid integration work to get features, and it can scale to support any amount of traffic and data. To deliver that, Vespa provides a broad range of query capabilities, a computation engine with support for modern machine-learned models, hands-off operability, data management, and application development support. It is free and open source to use under the Apache 2.0 license.
- Zilliz : Milvus is an open-source vector database, with over 18,409 stars on GitHub and 3.4 million+ downloads. Milvus supports billion-scale vector search and has over 1,000 enterprise users. Zilliz Cloud provides a fully-managed Milvus service made by the creators of Milvus. This helps to simplify the process of deploying and scaling vector search applications by eliminating the need to create and maintain complex data infrastructure. As a DBaaS, Zilliz simplifies the process of deploying and scaling vector search applications by eliminating the need to create and maintain complex data infrastructure.
- Weaviate : Weaviate is an open-source vector database used to store data objects and vector embeddings from ML-models, and scale into billions of data objects from the same name company in Amsterdam. Users can index billions of data objects to search through and combine multiple search techniques, such as keyword-based and vector search, to provide search experiences.
This sample makes of ChromaDB vector database, but you can easily modify the code to use another vector database. You can even use Azure Cache for Redis Enterprise to store the vector embeddings and compute vector similarity with high performance and low latency. For more information, see Vector Similarity Search with Azure Cache for Redis Enterprise
LangChain is a software framework designed to streamline the development of applications using large language models (LLMs) . It serves as a language model integration framework, facilitating various applications like document analysis and summarization, chatbots, and code analysis.
LangChain's integrations cover an extensive range of systems, tools, and services, making it a comprehensive solution for language model-based applications. LangChain integrates with the major cloud platforms such as Microsoft Azure, Amazon AWS, and Google, and with API wrappers for various purposes like news, movie information, and weather, as well as support for Bash, web scraping, and more. It also supports multiple language models, including those from OpenAI, Anthropic, and Hugging Face. Moreover, LangChain offers various functionalities for document handling, code generation, analysis, debugging, and interaction with databases and other data sources.
Chainlit is an open-source Python package that is specifically designed to create user interfaces (UIs) for AI applications. It simplifies the process of building interactive chats and interfaces, making developing AI-powered applications faster and more efficient. While Streamlit is a general-purpose UI library, Chainlit is purpose-built for AI applications and seamlessly integrates with other AI technologies such as LangChain , LlamaIndex , and LangFlow .
With Chainlit, developers can easily create intuitive UIs for their AI models, including ChatGPT-like applications. It provides a user-friendly interface for users to interact with AI models, enabling conversational experiences and information retrieval. Chainlit also offers unique features, such as the ability to display the Chain of Thought , which allows users to explore the reasoning process directly within the UI. This feature enhances transparency and enables users to understand how the AI arrives at its responses or recommendations.
For more information, see the following resources:
- Documentation
- API Reference
Deploy the Infrastructure
Before deploying the Terraform modules in the terraform/infra folder, specify a value for the following variables in the terraform.tfvars variable definitions file.
This is the definition of each variable:
- prefix : specifies a prefix for all the Azure resources.
- location : specifies the region (e.g., EastUS) where deploying the Azure resources.
NOTE : Make sure to select a region where Azure OpenAI Service (AOAI) supports both GPT-3.5 / GPT-4 models like gpt-35-turbo-16k and Embeddings models like text-embedding-ada-002 .
OpenAI Module
The following table contains the code from the terraform/infra/modules/openai/main.tf Terraform module used to deploy the Azure OpenAI Service .
Azure Cognitive Services use custom subdomain names for each resource created through the Azure portal , Azure Cloud Shell , Azure CLI , Bicep , Azure Resource Manager (ARM) , or Terraform . Unlike regional endpoints, which were common for all customers in a specific Azure region, custom subdomain names are unique to the resource. Custom subdomain names are required to enable features like Azure Active Directory (Azure AD) for authentication. In our case, we need to specify a custom subdomain for our Azure OpenAI Service as our chatbot applications will use an Azure AD security token to access it. By default, the terraform/infra/modules/openai/main.tf module sets the value of the custom_subdomain_name parameter to the lowercase name of the Azure OpenAI resource. For more information on custom subdomains, see Custom subdomain names for Cognitive Services .
This Terraform module allows you to pass an array containing the definition of one or more model deployments in the deployments variable. For more information on model deployments, see Create a resource and deploy a model using Azure OpenAI . The openai_deployments variable in the terraform/infra/variables.tf file defines the structure and the default models deployed by the sample:
As an alternative, you can use the Terraform module for deploying Azure OpenAI Service. to deploy an Azure OpenAI Service .
Private Endpoint Module
The terraform/infra/main.tf module creates Azure Private Endpoints and Azure Private DNDS Zones for each of the following resources:
In particular, it creates an Azure Private Endpoint and Azure Private DNDS Zone to the Azure OpenAI Service as shown in the following code snippet:
Below you can read the code of the terraform/infra/modules/private_endpoint/main.tf module, which is used to create Azure Private Endpoints :
Private DNS Zone Module
In the following box, you can read the code of the terraform/infra/modules/private_dns_zone/main.tf module, which is utilized to create the Azure Private DNS Zones .
Workload Managed Identity Module
Below you can read the code of the terraform/infra/modules/managed_identity/main.tf module, which is used to create the Azure Managed Identity used by the Azure Container Apps to pull container images from the Azure Container Registry , and by the chat applications to connect to the Azure OpenAI Service . You can use a system-assigned or user-assigned managed identity from Azure Active Directory (Azure AD) to let Azure Container Apps access any Azure AD-protected resource. For more information, see Managed identities in Azure Container Apps . You can pull container images from private repositories in an Azure Container Registry using user-assigned or user-assigned managed identities for authentication to avoid the use of administrative credentials. For more information, see Azure Container Apps image pull with managed identity . This user-defined managed identity is assigned the Cognitive Services User role on the Azure OpenAI Service namespace and ACRPull role on the Azure Container Registry (ACR) . By assigning the above roles, you grant the user-defined managed identity access to these resources.
Deploy the Applications
Before deploying the Terraform modules in the terraform/apps folder, specify a value for the following variables in the terraform.tfvars variable definitions file.
- resource_group_name : specifies the name of the resource group which contains the infrastructure resources: Azure OpenAI Service , Azure Container Registry , Azure Container Apps Environment , Azure Log Analytics , and user-defined managed identity .
- container_app_environment_name : the name of the Azure Container Apps Environment in which to deploy the chat applications.
- container_registry_name : the name of Azure Container Registry used to hold the container images of the chat applications.
- workload_managed_identity_name : the name of the user-defined managed identity used by the chat applications to authenticate with Azure OpenAI Service and Azure Container Registry .
- image : This field contains the name and tag of the container image but not the login server of the Azure Container Registry .
- identity : The identity of the container app.
- registry : The registry hosting the container image for the application.
- AZURE_CLIENT_ID : The client id of the user-defined managed identity used by the application to authenticate with Azure OpenAI Service and Azure Container Registry .
- AZURE_OPENAI_TYPE : This environment variable specifies the authentication type with Azure OpenAI Service : if you set the value of the AZURE_OPENAI_TYPE environment variable to azure, you need to specify the OpenAI key as a value for the AZURE_OPENAI_KEY environment variable. Instead, if you set the value to azure_ad in the application code, assign an Azure AD security token to the openai_api_key property. For more information, see How to switch between OpenAI and Azure OpenAI endpoints with Python .
Container App Module
The terraform/apps/modules/container_app/main.tf module is utilized to create the Azure Container Apps . The module defines and uses the following data source for the Azure Container Registry , Azure Container Apps Environment , and user-defined managed identity created when deploying the infrastructure. These data sources are used to access the properties of these Azure resources.
The module creates and utilizes the following local variables:
This is the explanation of each local variable:
- identity : uses the resource id of the user-defined managed identity to define the identity block for each container app deployed by the module.
- identity_env : uses the client id of the user-defined managed identity to define the value of the AZURE_CLIENT_ID environment variable that is appended to the list of environment variables of each container app deployed by the module.
- registry : uses the login server of the Azure Container Registry to define the registry block for each container app deployed by the module.
Here is the full Terraform code of the module:
As you can notice, the module uses the login server of the Azure Container Registry to create the fully-qualified name of the container image of the current container app.
Managed identities in Azure Container Apps
Each chat application makes use of a DefaultAzureCredential object to acquire a security token from Azure Active Directory and authenticate and authorize with Azure OpenAI Service (AOAI) and Azure Container Registry (ACR) using the credentials of the user-defined managed identity associated to the container app.
You can use a managed identity in a running container app to authenticate and authorize with any service that supports Azure AD authentication . With managed identities:
- Container apps and applications connect to resources with the managed identity. You don't need to manage credentials in your container apps.
- You can use role-based access control to grant specific permissions to a managed identity.
- System-assigned identities are automatically created and managed. They are deleted when your container app or container app is deleted.
- You can add and delete user-assigned identities and assign them to multiple resources. They are independent of your container app or the container app's lifecycle.
- You can use managed identity to authenticate with a private Azure Container Registry without a username and password to pull containers for your Container App.
- You can use managed identity to create connections for Dapr-enabled applications via Dapr components
For more information, see Managed identities in Azure Container Apps . The workloads running in a container app can use the Azure Identity client libraries to acquire a security token from the Azure Active Directory. You can choose one of the following approaches inside your code:
- Use DefaultAzureCredential , which will attempt to use the WorkloadIdentityCredential .
- Create a ChainedTokenCredential instance that includes WorkloadIdentityCredential .
- Use WorkloadIdentityCredential directly.
The following table provides the minimum package version required for each language's client library.
NOTE : When using Azure Identity client library with Azure Container Apps, the client ID of the managed identity must be specified. When using the DefaultAzureCredential , you can explicitly specify the client ID of the container app manged identity in the AZURE_CLIENT_ID environment variable.
Simple Chat Application
The Simple Chat Application is a large language model-based chatbot that allows users to submit general-purpose questions to a GPT model, which generates and streams back human-like and engaging conversational responses. The following picture shows the welcome screen of the chat application.

You can modify the welcome screen in markdown by editing the chainlit.md file at the project's root. If you do not want a welcome screen, leave the file empty. The following picture shows what happens when a user submits a new message in the chat.

Chainlit can render messages in markdown format and provides classes to support the following elements:
- Audio : The Audio class allows you to display an audio player for a specific audio file in the chatbot user interface. You must provide either a URL or a path or content bytes.
- Avatar : The Avatar class allows you to display an avatar image next to a message instead of the author's name. You need to send the element once. Next,, if an avatar's name matches an author's name, the avatar will be automatically displayed. You must provide either a URL or a path or content bytes.
- File : The File class allows you to display a button that lets users download the content of the file. You must provide either a URL or a path or content bytes.
- Image : The Image class is designed to create and handle image elements to be sent and displayed in the chatbot user interface. You must provide either a URL or a path or content bytes.
- Pdf : The Pdf class allows you to display a PDF hosted remotely or locally in the chatbot UI. This class either takes a URL of a PDF hosted online or the path of a local PDF.
- Pyplot : The Pyplot class allows you to display a Matplotlib pyplot chart in the chatbot UI. This class takes a pyplot figure.
- TaskList : The TaskList class allows you to display a task list next to the chatbot UI.
- Text : The Text class allows you to display a text element in the chatbot UI. This class takes a string and creates a text element that can be sent to the UI. It supports the markdown syntax for formatting text. You must provide either a URL or a path or content bytes.
Chainlit provides three display options that determine how an element is rendered in the context of its use. The ElementDisplay type represents these options. The following display options are available:
- Side : this option displays the element on a sidebar. The sidebar is hidden by default and opened upon element reference click.
- Page : this option displays the element on a separate page. The user is redirected to the page upon an element reference click.
- Inline : this option displays the element below the message. If the element is global , it is displayed if it is explicitly mentioned in the message. If the element is scoped , it is displayed regardless of whether it is expressly mentioned in the message.
You can click the user icon on the UI to access the chat settings and choose, for example, between the light and dark theme.
The application is built in Python. Let's take a look at the individual parts of the application code. In the following section, the Python code starts by importing the necessary packages/modules.
These are the libraries used by the chat application:
- os : This module provides a way of interacting with the operating system, enabling the code to access environment variables, file paths, etc.
- sys : This module provides access to some variables used or maintained by the interpreter and functions that interact with the interpreter.
- time : This module provides various time-related time manipulation and measurement functions.
- openai : The OpenAI Python library provides convenient access to the OpenAI API from applications written in Python. It includes a pre-defined set of classes for API resources that initialize themselves dynamically from API responses which makes it compatible with a wide range of versions of the OpenAI API. You can find usage examples for the OpenAI Python library in our API reference and the OpenAI Cookbook .
- random : This module provides functions to generate random numbers.
- logging : This module provides flexible logging of messages.
- chainlit as cl : This imports the Chainlit library and aliases it as cl . Chainlit is used to create the UI of the application.
- DefaultAzureCredential from azure.identity : when the openai_type property value is azure_ad, a DefaultAzureCredential object from the [Azure Identity client library for Python - version 1.13.0( https://learn.microsoft.com/en-us/python/api/overview/azure/identity-readme?view=azure-python ) is used to acquire security token from the Azure Active Directory using the credentials of the user-defined managed identity, whose client ID is defined in the AZURE_CLIENT_ID environment variable.
- load_dotenv and dotenv_values from dotenv : Python-dotenv reads key-value pairs from a .env file and can set them as environment variables. It helps in the development of applications following the 12-factor principles.
The requirements.txt file under the src folder contains the list of packages used by the chat applications. You can restore these packages in your environment using the following command:
Next, the code reads environment variables and configures the OpenAI settings.
Here's a brief explanation of each variable and related environment variable:
- temperature : A float value representing the temperature for Create chat completion method of the OpenAI API. It is fetched from the environment variables with a default value of 0.9.
- api_base : The base URL for the OpenAI API.
- api_key : The API key for the OpenAI API.
- api_type : A string representing the type of the OpenAI API.
- api_version : A string representing the version of the OpenAI API.
- engine : The engine used for OpenAI API calls.
- model : The model used for OpenAI API calls.
- system_content : The content of the system message used for OpenAI API calls.
- max_retries : The maximum number of retries for OpenAI API calls.
- backoff_in_seconds : The backoff time in seconds for retries in case of failures.
In the next section, the code sets the default Azure credential based on the api_type and configures a logger for logging purposes.
Here's a brief explanation:
default_credential : It sets the default Azure credential to DefaultAzureCredential() if the api_type is "azure_ad"; otherwise, it is set to None .
logging.basicConfig() : This function configures the logging system with specific settings.
- stream : The output stream where log messages will be written. Here, it is set to sys.stdout for writing log messages to the standard output.
- format : The format string for log messages. It includes the timestamp, filename, line number, log level, and the actual log message.
- level : The logging level. It is set to logging.INFO , meaning only messages with the level INFO and above will be logged.
logger : This creates a logger instance named after the current module ( __name__ ). The logger will be used to log messages throughout the code.
Next, the code defines a helper function backoff that takes an integer attempt and returns a float value representing the backoff time for exponential retries in case of API call failures.
The backoff time is calculated using the backoff_in_seconds and attempt variables. It follows the formula backoff_in_seconds * 2 ** attempt + random.uniform(0, 1) . This formula increases the backoff time exponentially with each attempt and adds a random value between 0 and 1 to avoid synchronized retries.
Then the application defines a function called refresh_openai_token() to refresh the OpenAI security token if needed.
The function follows these steps:
- It fetches the current token from cl.user_session (which seems to be a part of the chainlit library) using the key 'openai_token' . The user_session is a dictionary that stores the user’s session data. The id and env keys are reserved for the session ID and environment variables, respectively. Other keys can be used to store arbitrary data in the user’s session.
- It checks if the token is None or if its expiration time ( expires_on ) is less than the current time minus 1800 seconds (30 minutes).
Next, the code defines a function called start_chat that is used to initialize the when the user connects to the application or clicks the New Chat button.
Here is a brief explanation of the function steps:
- @cl.on_chat_start : The on_chat_start decorator registers a callback function start_chat() to be called when the Chainlit chat starts. It is used to set up the chat and send avatars for the Chatbot, Error, and User participants in the chat.
- cl.Avatar() : the Avatar class allows you to display an avatar image next to a message instead of the author name. You need to send the element once. Next if the name of an avatar matches the name of an author, the avatar will be automatically displayed. You must provide either a URL or a path or content bytes.
- cl.user_session.set() : This API call sets a value in the user_session dictionary. In this case, it initializes the message_history in the user's session with a system content message, which indicates the start of the chat.
Finally, the application defines the method called whenever the user sends a new message in the chat.
Here is a detailed explanation of the function steps:
- @cl.on_message : The on_message decorator registers a callback function main(message: str) to be called when the user submits a new message in the chat. It is the main function responsible for handling the chat logic.
- cl.user_session.get() : This API call retrieves a value from the user's session data stored in the user_session dictionary. In this case, it fetches the message_history from the user's session to maintain the chat history.
- message_history.append() : This API call appends a new message to the message_history list. It is used to add the user's message and the assistant's response to the chat history.
- cl.Message() : This API call creates a Chainlit Message object. The Message class is designed to send, stream, edit, or remove messages in the chatbot user interface. In this sample, the Message object is used to stream the OpenAI response in the chat.
- msg.stream_token() : The stream_token method of the Message class streams a token to the response message. It is used to send the response from the OpenAI Chat API in chunks to ensure real-time streaming in the chat.
- await openai.ChatCompletion.acreate() : This API call sends a message to the OpenAI Chat API in an asynchronous mode and streams the response. It uses the provided message_history as context for generating the assistant's response.
- The section also includes an exception handling block that retries the OpenAI API call in case of specific errors like timeouts, API errors, connection errors, invalid requests, service unavailability, and other non-retriable errors. You can replace this code with a general-purpose retrying library for Python like Tenacity .
Below, you can read the complete code of the application.
You can run the application locally using the following command. The -w flag` indicates auto-reload whenever we make changes live in our application code.
Documents QA Chat
The Documents QA Chat application allows users to submit up to 10 .pdf and .docx documents. The application processes the uploaded documents to create vector embeddings. These embeddings are stored in ChromaDB vector database for efficient retrieval. Users can pose questions about the uploaded documents and view the Chain of Thought , enabling easy exploration of the reasoning process. The completion message contains links to the text chunks in the documents that were used as a source for the response. The following picture shows the chat application interface. As you can see, you can click the Browse button and choose up to 10 .pdf and .docx documents to upload. Alternatively, you can just drag and drop the files over the control area.

After uploading the documents, the application creates and stores embeddings to ChromaDB vector database. During the phase, the UI shows a message Processing <file-1>, <file-2>... , as shown in the following picture:

When the code finished creating embeddings, the UI is ready to receive user's questions:

As your chat application grows in complexity, understanding the individual steps for generating a specific answer can become challenging. To solve this issue, Chainlit allows you to easily explore the reasoning process right from the user interface using the Chain of Thought . If you are using the LangChain integration, every intermediary step is automatically sent and displayed in the Chainlit UI just clicking and expanding the steps, as shown in the following picture:

To see the text chunks that were used by the large language model to originate the response, you can click the sources links, as shown in the following picture:

In the Chain of Thought , below each message, you can find an edit button, as a pencil icon, if that message was generated by a prompt. Clicking on it opens the Prompt Playground dialog which allows you to modify and iterate on the prompt as needed.

Let's take a look at the individual parts of the application code. In the following section, the Python code starts by importing the necessary packages/modules.
- time : This module provides various time-related functions for time manipulation and measurement.
- openai : the OpenAI Python library provides convenient access to the OpenAI API from applications written in the Python language. It includes a pre-defined set of classes for API resources that initialize themselves dynamically from API responses, which makes it compatible with a wide range of versions of the OpenAI API. You can find usage examples for the OpenAI Python library in our API reference and the OpenAI Cookbook .
- chainlit as cl : This imports the Chainlit library and aliases it as cl. Chainlit is used to create the UI of the application.
- DefaultAzureCredential from azure.identity : when the openai_type property value is azure_ad , a DefaultAzureCredential object from the Azure Identity client library for Python - version 1.13.0 is used to acquire security token from the Azure Active Directory using the credentials of the user-defined managed identity, whose client ID is defined in the AZURE_CLIENT_ID environment variable.
- langchain : Large language models (LLMs) are emerging as a transformative technology, enabling developers to build applications that they previously could not. However, using these LLMs in isolation is often insufficient for creating a truly powerful app - the real power comes when you can combine them with other sources of computation or knowledge. LangChain library aims to assist in the development of those types of applications.
- chat_completion_deployment : the name of the Azure OpenAI GPT model for chat completion.
- embeddings_deployment : the name of the Azure OpenAI deployment for embeddings.
- model : The model used for chat completion calls (e.g, gpt-35-turbo-16k ).
- max_size_mb : the maximum size for the uploaded documents.
- max_files : the maximum number of documents that can be uploaded.
- text_splitter_chunk_size : the maximum chunk size used by the RecursiveCharacterTextSplitter object.
- text_splitter_chunk_overlap : the maximum chunk overlap used by the RecursiveCharacterTextSplitter object.
- embeddings_chunk_size : the maximum chunk size used by the OpenAIEmbeddings object.
- system_template : The content of the system message used for OpenAI API calls.
The following code is used to initialize the large language model (LLM) chain used to reply to questions on the content of the uploaded documents.
The AskFileMessage API call prompts the user to upload up to a specified number of .pdf or .docx files. The uploaded files are stored in the files variable. The process continues until the user uploads files. For more information, see AskFileMessage .
The following code processes each uploaded file by extracting its content.
- The text content of each file is stored in the list all_texts .
- This code performs text processing and chunking. It checks the file extension to read the file content accordingly, depending on if it's a .pdf or a .docx document.
- The text content is split into smaller chunks using the RecursiveCharacterTextSplitter LangChain object.
- Metadata is created for each chunk and stored in the metadatas list.
- If openai.api_type == "azure_ad" , the code invokes the refresh_openai_token() that gets a security token from Azure AD to communicate with the Azure OpenAI Service.
The next piece of code performs the following steps:
- It creates an OpenAIEmbeddings configured to use the embeddings model in the Azure OpenAI Service to create embeddings from text chunks.
- It creates a ChromaDB vector database using the OpenAIEmbeddings object, the text chunks list, and the metadata list.
- It creates an AzureChatOpenAI LangChain object based on the GPR model hosted in Azure OpenAI Service.
- It creates a chain using the RetrievalQAWithSourcesChain.from_chain_type API call uses previously created models and stores them as retrievers.
- It stores the metadata and text chunks in the user session using the cl.user_session.set() API call.
- It creates a message to inform the user that the files are ready for queries, and finally returns the chain .
- The cl.user_session.set("chain", chain) call stores the LLM chain in the user_session dictionary for later use.
The following code handles the communication with the OpenAI API and incorporates retrying logic in case the API calls fail due to specific errors.
- cl.user_session.get("chain") : this call retrieves the LLM chain from the user_session dictionary.
- The for loop allows multiple attempts, up to max_retries , to communicate with the chat completion API and handles different types of API errors, such as timeout, connection error, invalid request, and service unavailability.
- await chain.acall : The asynchronous call to the RetrievalQAWithSourcesChain.acall executes the LLM chain with the user message as an input.
The code below extracts the answers and sources from the API response and formats them to be sent as a message.
- The answer and sources are obtained from the response dictionary.
- The sources are then processed to find corresponding texts in the user session metadata ( metadatas ) and create source_elements using cl.Text() .
- cl.Message().send() : the Message API creates and displays a message containing the answer and sources, if available.
Build Docker Images
You can use the src/01-build-docker-images.sh Bash script to build the Docker container image for each container app.
Before running any script in the src folder, make sure to customize the value of the variables inside the 00-variables.sh file located in the same folder. This file is embedded in all the scripts and contains the following variables:
The Dockerfile under the src folder is parametric and can be used to build the container images for both chat applications.
Test applications locally
You can use the src/02-run-docker-container.sh Bash script to test the containers for the sender , processor , and receiver applications.
Push Docker containers to the Azure Container Registry
You can use the src/03-push-docker-image.sh Bash script to push the Docker container images for the sender , processor , and receiver applications to the Azure Container Registry (ACR) .
Azure Container Apps provides several built-in observability features that together give you a holistic view of your container app’s health throughout its application lifecycle. These features help you monitor and diagnose the state of your app to improve performance and respond to trends and critical problems.
You can use the Log Stream panel on the Azure Portal to see the logs generated by a container app, as shown in the following screenshot.

Alternatively, you can click open the Logs panel, as shown in the following screenshot, and use a Kusto Query Language (KQL) query to filter, project, and retrieve only the desired data.

Review deployed resources
You can use the Azure portal to list the deployed resources in the resource group, as shown in the following picture:

You can also use Azure CLI to list the deployed resources in the resource group:
You can also use the following PowerShell cmdlet to list the deployed resources in the resource group:
Clean up resources
You can delete the resource group using the following Azure CLI command when you no longer need the resources you created. This will remove all the Azure resources.
Alternatively, you can use the following PowerShell cmdlet to delete the resource group and all the Azure resources.
Code of conduct
Contributors 2.
- Python 19.6%
- Dockerfile 4.7%
- Free Python 3 Course
- Control Flow
- Exception Handling
- Python Programs
- Python Projects
- Python Interview Questions
- Python Database
- Data Science With Python
- Machine Learning with Python

- Explore Our Geeks Community
- Select the right Weight for deep Neural Network in Pytorch
- Pandas read_csv: low_memory and dtype options
- Variable Length Argument in Python
- How to use numpy.argsort in Descending order in Python
- Increase the Font size of Editor
- Difference between Falcon and Flask
- How to Swap Two Rows in a NumPy Array
- Count the Number of Null Elements in a List in Python
- Different Ways of Using Inline if in Python
- How To List Installed Python Packages
- Difference Between os.rename and shutil.move in Python
- Use For Loop to Iterate Tuple in Python
- How to check NumPy version installed?
- Replacing Pandas or Numpy Nan with a None to use with MysqlDB
- Difference between NumPy and SciPy in Python
- How to fix FileNotFoundError in Python
- Python Falcon - Hello World
- Pandas: Detect Mixed Data Types and Fix it
- PyTorch Loss Functions
Convert String into Variable Name in Python
There may be situations where you want to convert a string into a variable name dynamically. In this article, we’ll explore how to convert a string into a variable name in Python with four simple examples.
While Python does not directly allow you to convert a string into a variable name, these examples demonstrate various approaches to achieve similar functionality using dictionaries, functions, exec(), or custom classes.
Example 1: Using a Dictionary
In this example, we use a dictionary (variable_dict) to associate string names with values. We dynamically create a variable name (variable_name) as a string, and then we store and retrieve its value using the dictionary. This approach allows us to mimic variable names with string keys.
Example 2: Using globals() and locals()
Here, we utilize the globals() function to create a global variable with a name defined by the string variable_name. This variable can be accessed throughout the program using the same string as its name.
Example 3: Using exec()
In this example, we use the exec() function to execute a dynamically generated Python code. We build a string containing the variable name and its value and then execute it. The result is a dynamically created variable accessible by its name.
Example 4: Using a Class
In this example, we create a class called VariableContainer to encapsulate the variables. This class provides methods for adding and retrieving variables using their names. By instantiating this class, you can dynamically add and access variables as needed.
Please Login to comment...

- Geeks Premier League 2023
- Geeks Premier League
Please write us at [email protected] to report any issue with the above content
Improve your Coding Skills with Practice

IMAGES
VIDEO
COMMENTS
name= ["deep","mahesh","nirbhay"] user_input = r"certi_ {element}" # this string I ask from user for element in name: print (f" {user_input}") This code gives output: certi_ {element} certi_ {element} certi_ {element} But I want: certi_ {deep} certi_ {mahesh} certi_ {nirbhay} How can I do this? python python-3.x string string-formatting f-string
The str.format () Method Doing String Interpolation With F-Strings in Python Interpolating Values and Objects in F-Strings Embedding Expressions in F-Strings Formatting Strings With Python's F-String Other Relevant Features of F-Strings Using an Object's String Representations in F-Strings Self-Documenting Expressions for Debugging
What are f-Strings in Python? Strings in Python are usually enclosed within double quotes ( "" ) or single quotes ( '' ). To create f-strings, you only need to add an f or an F before the opening quotes of your string. For example, "This" is a string whereas f"This" is an f-String. How to Print Variables using Python f-Strings
Option #1: %-formatting Here is to OG of Python format and has been in the language considering the very beginning. You can how view in the Python docs.
Using Variables in f-strings Programs commonly need to substitute a variable into a string. Python's f-strings provide a convenient way for us to do this. Let's consider an example: ocean_description = "deep blue" print(f"The ocean is {ocean_description} today") If we run this code, we'll receive output like the following: Output
How to write Python f-strings. You write Python f-strings by writing two parts: f (or F) and a string (either single, double, or triple quotes). So, an f-string can look like this: fstring = f'string' Where string is replaced by the string you want to use. Displaying variables with f-strings. f-strings make it incredibly easy to insert ...
Python Assign String Variables Python String Variables Python Glossary Assign String to a Variable Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example Get your own Python Server a = "Hello" print(a) Try it Yourself » String Length Check In String Python Glossary SPACES UPGRADE
To create an f-string, prefix the string with the letter " f ". The string itself can be formatted in much the same way that you would with str.format (). F-strings provide a concise and convenient way to embed python expressions inside string literals for formatting. Code #1 : Python3. val = 'Geeks'. print(f" {val}for {val} is a portal for ...
An f string are prefixed with "f" at the start, before the string iitself begins. Introduced in Python 3.6, make it easier to format strings. f strings use curly braces to store the values which should be formatted into a string. f strings can also use a capital "F" to represent a formatted string. Consider this syntax:
I have a variable with a string assigned to it and I want to define a new variable based on that string. foo = "bar" foo = "something else" # What I actually want is: bar...
dictOfStuff = {} ##Make a Dictionary x = "Buffalo" ##OR it can equal the input of something, up to you. dictOfStuff [x] = 4 ##Get the dict spot that has the same key ("name") as what X is equal to. In this case "Buffalo". and set it to 4. Or you can set it to what ever you like print (dictOfStuff [x]) ##print out the value of the spot in the ...
Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example a = "Hello" print (a) Try it Yourself » Multiline Strings You can assign a multiline string to a variable by using three quotes: Example You can use three double quotes: a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit,
Another way to parse the string would be to use json.loads: import json data_str = ' [53, 2]' data = json.loads (data_str) data will then be the list [53, 2]. Then you can get x and y the same way as above: x, y = data. Thanks to _habnabit in the #python IRC channel on FreeNode for pointing this out. :)
1. Use the index by listing it through the python list () function. For example, Like this. k = '010' result = list (k) print (result [0]) If there is no criteria to distinguish such as a gap, I think the list () is more comfortable than .split (). Share. Improve this answer. Follow. edited Nov 7, 2021 at 8:26.
The {number:<5} part tells Python to take the output of number.__format__("<5") and use that as the string value to combine with the rest of the string, in between the [and ] parts. This still doesn't change what the number variable references, however.
-1 This question already has answers here : How do I escape curly-brace ( {}) characters in a string while using .format (or an f-string)? (23 answers) How to escape curly-brackets in f-strings? [duplicate] (1 answer) Closed 2 years ago. data = f'" {name}": ' + " {" + tmp + "},"
6 Answers Sorted by: 21 You can use the operator % to inject strings into strings: "first string is: %s, second one is: %s" % (str1, "geo.tif") This will give: "first string is: STR1CONTENTS, second one is geo.tif" You could also do integers with %d: "geo%d.tif" % 3 # geo3.tif Share Improve this answer Follow edited Jul 29, 2010 at 22:09
1. Using exec () Method in Python to Convert a Python string to a Variable Name The Exec () methods helps us to execute the python program dynamically. In this example, we will have a variable named by us and an input string. We will then be applying the exec () method with some modifiers and trying to convert a string into a variable name.
return. print (i) To fix this, replace the "return" statement with a "break" statement like the next code block. By doing this, the "break" statement will correctly stop the loop when "i" exceeds 15, and Python will not raise a "SyntaxError". # This WORKS. items = range (1, 100) # print the first 15 items.
In Java, there are different types of variables, for example: String - stores text, such as "Hello". String values are surrounded by double quotes. int - stores integers (whole numbers), without decimals, such as 123 or -123. float - stores floating point numbers, with decimals, such as 19.99 or -19.99. char - stores single characters, such as ...
Here's a brief explanation of each variable and related environment variable: temperature: A float value representing the temperature for Create chat completion method of the OpenAI API. It is fetched from the environment variables with a default value of 0.9. api_base: The base URL for the OpenAI API. api_key: The API key for the OpenAI API.
While Python does not directly allow you to convert a string into a variable name, these examples demonstrate various approaches to achieve similar functionality using dictionaries, functions, exec (), or custom classes. Example 1: Using a Dictionary In this example, we use a dictionary (variable_dict) to associate string names with values.