This question already has answers here:
My variable is defined but python is saying it isn't?
(2 answers)
Closed 4 years ago.
I seek advice on a matter relating to this function.
I have tried various editing and indentation on the code, but it is showing the same result.
It shows NameError: name 'sentence' is not defined although I have defined it in the function.
The code is:
def about (name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
about ("Jack", 23, "programming")
print (sentence)
You should call function and assign it to an variable:
def about(name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
Then
val = about("Jack", 23, "programming")
print(val)
you can also use sentence instead of val but this will not be the same sentence in function scope.
try this now....
def about (name, age, likes):
sentence = "Meet {}, he is {} years old and likes {}".format(name,age,likes)
return sentence
print(about('rohit',23,'programming'))
sentense scope is bounded to about function... and trying to print it out of the function scope may not work.
Related
This question already has answers here:
How to postpone/defer the evaluation of f-strings?
(14 answers)
Closed yesterday.
This post was edited and submitted for review yesterday.
I have some variables, some of them came from another functions:
dogs = calculate_dogs()
name = random_owner()
city = gps_position()
sentence = '{name} has {dogs} dog(s) and lives in {city}'
To print, I would normally add one f like this:
print(f'{name} has {dogs} dog(s) and lives in {city}')
But since this variable called sentence comes "as is" from somewhere else, what can I do to print it (or anything else)?
I first tried this, unsuccessfully:
print(f'{sentence}')
For now I made a kinda nasty workaround like this:
sentence = sentence.replace('{name}', name)
sentence = sentence.replace('{dog}', dog)
sentence = sentence.replace('{city}', city)
print(sentence)
Any ideas?
Edited question: Since the variables are coming from different sources, it doesn't seem to work a dictionary, or I just don't do it right.
I tried:
variables = {'dogs' : calculate_dogs(), 'name' : random_owner(), 'city' : gps_position()}
You can call str.format and pass the variable values as keyword arguments.
sentence = '{name} has {dogs} dog(s) and lives in {city}'
variables = {'dogs' : 1, 'name' : 'Bob', 'city' : 'LA'}
print(sentence.format(**variables))
This question already has answers here:
partial string formatting
(23 answers)
Closed 7 months ago.
I want to create a string template that only selected parameters gets value in each session.
For example:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much"
s.format(fruits_num=fruits_num, fruit_name='apple')
s.format(fruits_num=fruits_num, fruit_name='orange')
I want to avoid the repeated assignment of fruits_num=fruits_num
In a pseduo code:
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {fruit_name} very much".format(fruits_num=fruits_num)
s.format(fruit_name='apple')
s.format(fruit_name='orange')
I this possible? Thanks.
You can double the { around fruits_name so that it will be literal, which will keep it until the next call to .format().
def format_fruits(fruits_num):
s = "I have {fruits_num} and I like {{fruit_name}} very much".format(fruits_num=fruits_num)
print(s.format(fruit_name='apple'))
print(s.format(fruit_name='orange'))
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 1 year ago.
I am working in Python trying to write a function using a list of variables.
Here is the data I am working with:
material_list=['leather', 'canvas', 'nylon']
def materialz(MAT):
MAT=support.loc[(material==MAT)].sum()
for i in enumerate(material_list):
materialz(i)
What I am looking for is to pass in each of the items in the list to the function to produce global variables.
leather=
canvas=
nylon=
Any help would be appreciated!
You could create a dictionary and dynamically assign the key-value pairs there. Such as:
material_list=['leather', 'canvas', 'nylon']
material_dict={}
for i in enumerate(material_list):
material_dict[i]=value #Where i would be the key and value the value in the key-value pair
you can use exec
var = 'hello'
output = hello
exec('var = "world"')
print(var)
output = world
This question already has answers here:
Python — check if a string contains Cyrillic characters
(4 answers)
Closed 3 years ago.
I have a task to write a function that adds "Hello, " and "Привет" if a name in the list is English or Russian and then returns a tuple. For example, we have ["Mary", "Kate", "Маша", "Alex"]. Our function should return a tuple like this: ('Hello, Mary', 'Hello, Kate', 'Привет, Маша', 'Hello, Alex). I have no idea how to achieve this. I can add Hello to all elements, but what to do with this Привет I don't know.
What I came up with so far...
Please help!
def name(my_list):
for x in my_list:
new_lis = ["Hello, " + x for x in my_list]
new_lis1 = tuple(new_lis)
print(new_lis1)
name(my_list)
this isn't really the type of website, were you post your question and someone else finds the answer for you - but you are in luck, and someone had the exact same question before.
Following the answers in the linked thread, you could do something like:
def salutation_name(name):
if all([c in '[а-яА-Я]' for c in name]):
return f'Привет {name}'
else:
return f'Hello {name}'
names = ["Mary", "Kate", "Маша", "Alex"]
print([salutation_name(name) for name in names])
This question already has answers here:
Access to value of variable with dynamic name
(3 answers)
Closed 6 years ago.
I am using a function that assigns a variable to equal the value of a randomly chosen key. Here the type is string and print works.
def explore():
import random
random_key = random.choice(explore_items.keys())
found_item = explore_items[random_key]
print type(found_item)
print found_item
Then, I want to use the variable name 'found_item' to call a dictionary of the same name, eg:
print found_item['key_1']
But I get the error, "TypeError: string indices must be integers, not str"
How would I use a string to call a previously defined dictionary that shares the same name?
You can use a variable via its name as string using exec:
dic1 = {'k': 'dic2'}
dic2 = {'key_1': 'value'}
exec('print ' + dic1['k'] + "['key_1']")
Short answer: I don't think you can.
However, if the dictionary explore_items uses the dicts in questions as its keys, this should work.
ETA to clarify:
explore_items = {{dict1}: a, {dict2}:b, {dict3}:c}
random_key= random.choice(explore_items.keys())