User input into a string Python 2.7 - python

I'm trying to enter user input into a string in two places in python 2.7.12
I want it to look something like this
import os
1 = input()
2 = input()
print os.listdir("/home/test/1/2")
I know you can use .format() to input into string but the only way I know how to do it is
print os.listdir("/home/test/{0}".format(1))
but I couldn't figure out how to enter a second input into the string.
sorry for any confusion, I'm kinda new to Stack Overflow. If you have any questions please ask.

import os
segment1 = input()
segment2 = input()
print os.listdir("/home/test/{}/{}".format(segment1, segment2))
1 and 2 are not legal variable names, so 1 = input() will cause an error.
You can use as many variables as you want in your format string; just pass them as additional parameters to .format(...). In the format string, you can use {0}, {1}, etc., or you can just use {} positionally. (The first {} refers to the first parameter, the second {} to the second parameter, etc.).

Related

Python: Using bool() to select which vars are TRUE, then use those values to call function

First question ever! I've built a GUI which asks user to input 2 of possible 5 values. Each pair of values (10 possible pairs) get used to run 10 different solution functions named Case_n to which all five values (both zero and non-zero) are passed.
The problem I'm having is getting the bool() results stripped down to 2 digit without brackets, etc and then placed into a variable used to create the name of the function to call.
I've run the logic, with TRUE values added to a list, then converted the list to a string so I could strip it down to just the numerals, saved the 2 digit string and added it to the Case_n name. Now, when I try to use the name to call the function, I get an error that a string is not callable. Please help . . .
s = 5 #vars. For this example, I've pre-loaded 2 of them
a = 15
l = 0
r = 0
e_deg = 0
ve = 0
case = []
if bool(s):
case.append(1)
if bool(a):
case.append(2)
if bool(l):
case.append(3)
if bool(r):
case.append(4)
if bool(e_deg):
case.append(5)
nm = str(case) # placeholder to convert case to string
case_num = nm[1] + nm[4] # this returns 12 as a string
# create case_num var, using the string
Case = "Case_" + case_num
print("Case = ",Case) # Should be Case_12
def Case_12(s,a,l,r,e_deg,ve):
print("Case_12 running")
Case(s,a,l,r,e_deg,ve) ```
You could just use eval(Case) but I advise against it as you are processing user input and it could be a security risk.
An easy way would be to build the following dict :
my_dict = {"Case_1": Case_1, ..., "Case_12" : Case_12}
And then, instead of calling Case, you would do
my_dict[Case](s,a,l,r,e_deg,ve)
You could also create a function :
def choose_case(my_case_as_str):
my_case_dict = {"Case_1": Case_1, ..., "Case_12": Case_12}
return my_case_dict[my_case_as_str]
And then call
choose_case(Case)(s,a,l,r,e_deg,ve)
By the way, you probably don't want your function and variable names to start with an uppercase letter. You also probably want to use a safer way to get user input (for example use Template str)

What does format() in Python actually do?

I'm coming into Python3 after spending time with Ruby, R, and some Java. Immediately I've come across the format() function and I'm a little lost as to what it does. I've read Python | format() function and see that it somehow resembles this in ruby:
my_name = "Melanie"
puts "My name is #{my_name}."
Outputs:
"My name is Melanie."
However, I don't understand why I can't just use a variable as above. I must be very much misunderstanding the usage of the format() function. (I'm a novice, please be gentle.)
So what does format() actually do?
You can definitely use a variable in the string example that you have shown, in the following manner:
my_name = "Melanie"
Output = "My name is " + my_name + "."
print(Output)
My name is Melanie.
This is the easy way, but not the most elegant.
In the above example, I have used 3 lines and created 2 variables (my_name and Output)
However, I can get the same output using just one line of code and without creating any variables, using format()
print("My name is {}.".format("Melanie"))
My name is Melanie.
Curly braces {} are used as placeholders, and the value we wish to put in the placeholders are passed as parameters into the format function.
If you have more than one placeholder in the string, python will replace the placeholders by values, in order.
Just make sure that the number of values passed as parameters to format(), is equal to the number of placeholders created in the string.
For example:
print("My name is {}, and I am {}.".format("Melanie",26))
My name is Melanie, and I am 26.
There are 3 different ways to specify placeholders and their values:
Type 1:
print("My name is {name}, and I am {age}.".format(name="Melanie", age=26))
Type 2:
print("My name is {0}, and I am {1}.".format("Melanie",26))
Type 3:
print("My name is {}, and I am {}.".format("Melanie",26))
Additionally, by using format() instead of a variable, you can:
Specify the data type, and
Add a formatting type to format the result.
For example:
print("{0:^7} has completed {1:.3f} percent of task {2}".format("Melanie",75.765367,1))
Melanie has completed 75.765 percent of task 1.
I have set the data type for the percentage field to be a float, with 3 decimals, and given a character length of 7 to the name, and center-aligned it.
The alignment codes are:
' < ' :left-align text
' ^ ' :center text
' > ' :right-align
The format() method is helpful when you have multiple substitutions and formattings to perform on a string.
The format function is a method for string in python, it is use to add a variable to string. for example:
greetings = 'hello {0}'
visitor = input('please enter your name')
print(greetings.format(visitor))
it can also be use to pad/position string also, thisn actually align the visitor into to the greetings in 10 byte of space
greetings = 'hello {0:^10}'
visitor = input('please enter your name')
print(greetings.format(visitor))
Also, there are two type of format in python 3x: the format expression and the format function.
the format expression is actually this '%'
and many more on 'format'. Maybe you should check on the doc 'format' by typing "help(''.format)"
An example using the format function is this:
name = Arnold
age = 5
print("{ }, { }".format(name, age))
This displays:
Arnold, 5

Pulling variables out of functions in Python

I have been self-teaching Python for a few weeks now and have the aim to create a script to run an equation and keep hitting walls. What I basically want to do is take an input with a unit attached i.e. 6M being 6,000,000, convert the unit into a numerical format and put that into an equation with an output.
So far I have defined a function:
def replaceunit(body):
body = body.replace(str(body[-1]),str(units.get(body[-1])))
return body
I have asked for the input and have a dictionary of units (shortened dictionary below):
T = input("T = ")
B = input("B = ")
units ={'M': 1e6, # mega
'G': 1e9 # giga
}
I then try and replace the if an M or G appears in the T or B variables:
if str(T[-1]).isalpha() == True:
replaceunit(T)
if str(B[-1]).isalpha() == True:
replaceunit(B)
After this I would like the updated T and B to be put into an equation that I define.
If I add a print action to my function I can see the values have been replaced, but have been unable to pull the corrected values through outside of the function and into another equation.
As I say, I'm very new to this, so if there's any help you can lend I'd very much appreciate it. Apologies also if this has been asked elsewhere, the few similar answers I have seen I haven't really understood the answer too.
Strings are immutable in Python, meaning they cannot be changed in place, but rather you have to create a new string for every change. That is exactly what you did in replaceunit - you wrote body = body.replace(...) and you replaced the old reference with a new one that replace gave you.
replaceunit is also returning a new reference, so calling it should be done as T = replaceunit(T) and B = replaceunit(B) to save changes. You must not use the same variable if you want to save both the replaced and non-replaced versions of the string.
If you want the value you returned from replaceunit to be the new value of T, you need to assign it:
T = replaceunit(T)
Note that you could skip the step of assigning body inside the function itself and simply return the value:
def replaceunit(body):
return body.replace(str(body[-1]),str(units.get(body[-1])))
I would also suggest that it might be more useful to have a function that turns the user-inputted number into an actual number:
def parse_number(body: str) -> float:
"""Converts a string like '2G' into a value like 2000000000."""
units ={
'M': 1e6, # mega
'G': 1e9, # giga
}
return float(body[:-1]) * units[body[-1]]
This will be necessary if you want to do any actual math with that value!

There's an issue with Input in my Python code

so I'm a beginner in python and I was trying to get an input function to work. It looks to me like Python isn't taking the data I give it, like it's not reading user input correctly. here is my code:
var = input
input("press ENTER to choose an app")
if var==1:
clock()
elif var==2:
oshelp()
elif var==3:
ebooks()
elif var==4:
what_is_new()
else:
print("Application Not Found.")
right now, the IDLE just prints "Application Not Found" even when i type a valid number and I'm not sure why. can anyone help me with this? (please include examples). Thanks!
Your issue occurs on the first line
var = input
You are setting var equal to the function input, not the returning value.
How you have it, if you were to write x = var("Enter: "), this would do the same as x = input("Enter: ").
You actually need to do var = input("Enter: "), but this will return a value, of type string, so when you compare this value to 1, even if the user enters 1, it will return false, as they are different data types.
You can either cast the input to an integer value, or compare the inputted value to strings.
var = input("Enter: ")
if var == "1":
or
var = int(input("Enter: "))
if var == 1
I would personally use the top one, as the program wouldn't crash if entered a non-int value.
Hope this helps!
The input will be a string and not ints. You can change your conditions from checking var == 1 to var == "1" etc. Or you can create an int from the input, using int(input()). However beware of the case where the input is not convertible to an int in that case an exception will be thrown.
input returns a string, but you're checking it against ints. One way to do this would be to check the input, as explained here. You could also just compare it to strings:
if var == '1':
Or convert the input to an int directly:
var = int(input(...))
Be careful with the last one, as it will fail if the user does not input a valid int.
The python input returns a string and you are comparing ints. If you would like to compare ints, then:
inputInt = int(input("please ENTER"))
or you could use eval
inputInt = eval(input("please ENTER"))
be careful with eval as it can cause problems, but it will handle just numbers and floats for you.

Can we make python take variables than strings from raw_input() builtin function?

I want to know if there is anyway I can have python raw_input() to procure a variable call for me.
what I understand is that, raw_input() takes whatever comments written in it and convert it to string, much like %r, it just prints everything in what I understand as a debugging mode string formatted.
but if we attempt to convert something like this:
test1 = int(raw_input("Please write some number:> "))
print test1 * 100
and if we input 100, the next line will perform a calculation function on it, something I am very interested to implement but in this way:
This isn't a false attempt but to give a general idea of what I want
a = "I will like some candies"
b = "I will like some chocolates"
c = "I will rather die but have fried chicken"
test2 = raw_input("Please write the variable name you want to print"
If this was the way python would take the inputs like, we will have a printed for example when the input was given as a and so on with b and c etc.
Is there a way in python to get the program to get an input from us in form of a variable than string. Any conversions?
Thank you all for your help in advance...
No, As you said raw_input returns a string. If you you want to return a relevant result based on user input, the best way is using a dictionary for mapping your variable names to their values:
my_dict = {'a': "I will like some candies"
'b': "I will like some chocolates"
'c': "I will rather die but have fried chicken" }
test2 = raw_input("Please write the variable name you want to print"
warning = "Please choose one of the aforementioned choices (a, b, c)"
print my_dict.get(test2,warning)
If it's a global variable, then you can do:
test1 = int(raw_input("Please write some number:> "))
print test1 * 100
a = "I will like some candies"
b = "I will like some chocolates"
c = "I will rather die but have fried chicken"
test2 = raw_input("Please write the variable name you want to print ")
print globals()[test2]
If not, you'll have to specify the namespace of your variable.

Categories