I am completely new to any coding at all.
As one of my first little tasks I tried to design a program comparing numbers. I wanted to add a function that distinguishes "pi" and "e" entries and converts them into respective floats. This function, however, doesnt work fine.
# the user is prompted to insert a value. This will be stored `enter code here`as "input1"
input1=input("insert a number:")
# decide whether the input is a number or a word. Convert words `enter code here`into numbers:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", (number))
elif pismeno == "e":
number= float(2.71)
print ("word e converted to number:", (number))
else:
number = float(pismeno)
print (number, "is already a number. No need to convert.")
# call the convert function onto the input:
convert(input1)
print ("The number you chose is:",input1)*
I guess that it has something to do with the output being stored inside the function and not "leaking" outside to the general code. Please keep in mind that I have literally NO experience so stick to a child language rather than the usual professional speech.
If you are writing a function, you need a return statement. A simplified example of your code:
def convert(pismeno):
if pismeno == "pi":
number=float(3.14)
print ("word pi converted to number:", number)
return number
else:
....
....
input1=input("insert a number:")
print(convert(input1))
I really suggest you to study basic concepts of programming. You may start here: https://www.learnpython.org/. More about functions: https://www.learnpython.org/en/Functions
The number you chose is: pi" instead of "The number you chose is: 3.14"
Your current final print just prints the input you originally gave it (input1)
You need to provide a way to return a value from the function and then set that to a variable where you call it
def convert(pismeno):
... Code ...
return number
# call the convert function onto the input:
output_num = convert(input1)
print ("The number you chose is:",output_num )
Related
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for i in range(len(quizes)):
grade = eval(input("Enter", quizes[i][0],"grade:"))
quizes[i].append(grade)
print(quizes[i])
Hey guys so I been working on this for the past week and can't solve this. I am trying to get my program to ask "Enter [person1] grade: " and so on and append a second element to each sublist which will be their grade and then print the contents of the entire list. Any help is appreciated
The problem is input takes 1 string as a parameter, you are passing 3 instead. So:
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
grade = eval(input(f"Enter {l[0]} grade:"))
l.append(grade)
print(l)
However, I respectfully don't understand the point of using eval here. Eval turns data into code. Using eval on user input creates a great security hole. In the above code, what if the user input quizes.clear()? The whole array will be emptied. What if he inputs something eviler?
Consider (assumes valid grades only contain numbers):
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for l in quizes:
while True:
try:
grade = float(input(f"Enter {l[0]} grade:"))
except ValueError:
print("Please input a number.")
else:
l.append(grade)
break
print(quizes)
The main problem is that input() accepts only one argument as the input prompt, unlike print which can take any number of arguments - you're giving 3 parameters to the input function - "Enter", quizes[i][0], and "grade:".
You can try concatenating them - like input("Enter "+str(quizes[i][0])+" grade:") (the str() conversion is not needed if you know that all the quizes[i][0] will be strings already),
or even use string formatting - "Enter {} grade".format(quizes[i][0]) or f"Enter {quizes[i][0]} grade:"
This should be enough, but there are 2 more changes you can make to your code if you like -
Iterate over the nested lists directly (for sub_list in quizes:)
Using int() or float() to convert a returned input string containing a number will also work in place of eval
For example
for quiz in quizes:
grade = eval(input("Enter {} grade:".format(quiz[0])))
quiz.append(grade)
print(quiz)
EDIT: Python docs on string formatting The f"..." syntax works only for Python 3.6+
You need to change:
grade = eval(input("Enter", quizes[i][0],"grade:"))
to
grade = eval(input("Enter " + quizes[i][0] + " grade:"))
input does not behave as print does. You can't use commas to join text in any other function (except for a very small number of custom functions and modules), and you should stay away from them at if that's confusing for you to only use them sometimes.
With that change, does your code work now? You didn't tell us why it wasn't working the way you expected.
Now that I'm looking at it, what did yours do wrong?
quizes = [["Andrew"], ["Amy"], ["Jared"], ["Bob"], ["Sarah"]]
for quiz in quizes:
grade = eval(input("Enter " + quiz[0] + " grade:"))
quiz.append(grade)
print(quiz)
print(quizes)
Thanks firstly for bearing with me as a relative newcomer to the world of Python. I'm working on a simple set of code and have been racking my brain to understand where I am going wrong. I suspect it is a relatively simple thing to correct but all searches so far have been fruitless. If this has been covered before then please be gentle, I have looked for a couple of days!
I'm working on the following and after catching and correcting a number of issues I suspect that I'm on the last hurdle:-
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(our_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(our_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(our_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
main()
else:
print("Goodbye")
break`
For some reason the appended (our_list) is not being recognised within the while true loop rendering the statistics calculation void. Any steer would be really appreciated as to where I am missing the obvious, thanks in advance.
Cheers
Bryan
I'm not sure exactly what you mean by "not being recognized", but our_list is a local variable inside main, so it can't be used anywhere but inside main.
So, if you try to use it elsewhere, you should get a NameError.
If your code actually has a global variable with the same name as the local variable that we aren't seeing here, things can be more confusing—you won't get a NameError, you'll get the value of the global variable, which isn't what you want.
The best solution here is to return the value from the function, and then have the caller use the returned value. For example:
def main():
our_list = []
ne = int(input('How many numbers do you wish to enter? '))
for i in range(0, (ne)): # set up loop to run user specified number of time
number=int(input('Choose a number:- '))
our_list.append(number) # append to our_list
print ('The list of numbers you have entered is ')
print (our_list)
return our_list
the_list = main()
while True:
op = input ('For the mean type <1>, for the median type <2>, for the mode type <3>, to enter a new set of numbers type <4> or 5 to exit')
import statistics
if op == "1":
mn = statistics.mean(the_list)
print ("The mean of the values you have entered is:- ",mn)
if op == "2":
me = statistics.median(the_list)
print ("The median of the values you have entered is:- ",me)
if op == "3":
mo = statistics.mode(the_list)
print ("The mode of the values you have entered is:- ",mo)
if op == "5":
the_list = main()
else:
print("Goodbye")
break
There are other options—you could pass in an empty list for main to fill, or use a global variable (or, better, a more restricted equivalent like an attribute on a class instance or a closure variable), or refactor your code so everyone who needs to access our_list is inside the same function… but I think this is the cleanest way to do what you're trying to do here.
By the way, this isn't quite the last hurdle—but you're very close:
After any mean, median, or mode, it's going to hit the "Goodbye" and exit instead of going back through the loop. Do you know about elif?
You mixed up '5' and '4' in the menu.
If the user enters 2 and 3 and asks for the mode, your code will dump a ValueError traceback to the screen; probably not what you want. Do you know try/except?
That's all I noticed, and they're all pretty simple things to add, so congrats in advance.
The issue is that our_list was defined in the main() function, and is not visible outside of the main() function scope.
Since you're doing everything in one chunk, you could remove line 1 and 6, taking the code from your main() function and putting it on the same indentation level as the code which follows.
This seems to be because you defined our_list within the main() function. You should probably define it as a global variable by creating it outside the main() function.
You could also put the while loop inside a function and pass in our_list as a parameter to the list.
I am trying to write a code for squaring the user input number in Python. I've created function my1() ...
What I want to do is to make Python to take user input of a number and square it but if user added no value it gives a print statement and by default give the square of a default number for e.g 2
Here is what I've tried so far
def my1(a=4):
if my1() is None:
print('You have not entered anything')
else:
b=a**2
print (b)
my1(input("Enter a Number"))
This is a better solution:
def my1(a=4):
if not a:
return 'You have not entered anything'
else:
try:
return int(a)**2
except ValueError:
return 'Invalid input provided'
my1(input("Enter a Number"))
Explanation
Have your function return values, instead of simply printing. This is good practice.
Use if not a to test if your string is empty. This is a Pythonic idiom.
Convert your input string to numeric data, e.g. via int.
Catch ValueError and return an appropriate message in case the user input is invalid.
You're getting an infinite loop by calling my1() within my1(). I would make the following edits:
def my1(a):
if a is '':
print('You have not entered anything')
else:
b=int(a)**2
print (b)
my1(input("Enter a Number"))
When I read your code, I can see that you are very confused about what you are writing. Try to organize your mind around the tasks you'll need to perform. Here, you want to :
Receive your user inputs.
Compute the data.
Print accordingly.
First, take your input.
user_choice = input("Enter a number :")
Then, compute the data you received.
my1(user_choice)
You want your function, as of now, to print an error message if your type data is not good, else print the squared number.
def my1(user_choice): # Always give meaning to the name of your variables.
if not user_choice:
print 'Error'
else:
print user_choice ** 2
Here, you are basically saying "If my user_choice doesn't exists...". Meaning it equals False (it is a bit more complicated than this, but in short, you need to remember this). An empty string doesn't contain anything for instance. The other choice, else, is if you handled your error case, then your input must be right, so you compute your data accordingly.
In your second line, it should be
if a is None:
I think what you want to do is something like the following:
def m1(user_input=None):
if user_input is None or isinstance(user_input, int):
print("Input error!")
return 4
else:
return int(user_input)**2
print(my1(input("Input a number")))
pseudocode
numtodouble=int
result=int
print("")
print("Enter a number you would like to double and press Enter.")
input (numtodouble)
<class 'int'>2
'2'
while numtodouble>0:
result=numtodouble*2
print("2 X", numtodouble, "=", result)
print("")
print("Enter a number you would like to double and press Enter.")
input(numtodouble)
break
print("OK, you entered a value <=0, ending execution.")
Does anyone know where I went wrong with my code? I've been struggling with this for hours.
try:
# input is stored as num_to_double. the input is cast to an int, and the string in input is the prompt
num_to_double = int(input("Enter a number you would like to double and press Enter."))
while num_to_double>0:
result=num_to_double*2
# Format puts the arguments into the curly braces in the order given
print("2 X {} = {}\n".format(num_to_double, result))
# input is cast to int and stored in num_to_double. The text in the input command is the prompt
num_to_double =int(input("Enter a number you would like to double and press Enter."))
# This is otuside the while loop, so this runs when the while loop breaks. The previous break command was making
# the code act not as intended
print("OK, you entered a value <=0, ending execution.")
# This catches if someone inputs a value that is not able to be cast to a string. It's the second half of the Try:
# Except block.
except ValueError as _:
print("A not-a-number was supplied")
This code is far simplier and does what you're trying to do. I assume you're learning python, so some of these things are not the simplest way to do things, like the format function, but are super useful to learn.
num_to_double = 0
result = 0
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
while num_to_double > 0:
result = num_to_double * 2
print("2 X {} = {}".format(num_to_double, result))
print("")
num_to_double = int(input("Enter number would you like to double and press enter."))
print("OK< you entered a value <=0, ending execution.")
This code is the closest I could do to the pseudocode provided. Declaring variables before they're used here isn't necessary and is messy. It's like the pseudocode wasn't meant to become python. Same with printing blank lines, those should be wrapped into the previous or next print lines.
I want to make this code much more elegant, using loop for getting user input into a list and also making the list as a list of floats withot having to define each argument on the list as a float by itself when coming to use them or print them...
I am very new to python 3.x or python in general, this is the first code i have ever written so far so 'mercy me pardon!'
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n
if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
calc =list(range(2))
calc[0] = (input("number 1:"))
calc[1] = (input("number 2:"))
print (float(calc[0])/float(calc[1]))
Since you are saying you are new to Python, I'm going to suggest you experiment with a few methods yourself. This will be a nice learning experience. I'm not going to give you answers directly here, since that would defeat the purpose. I'm instead going to offer suggestions on where to get started.
Side note: it's great that you are using Python3. Python3.6 supports f-strings. This means you can replace the line with your print function as follows.
print(f"Hello {Name} What's up? "
"\nare you coming to the party tonight in {Place}"
"\n if not at least try to make simple calculator:")
Okay, you should look into the following in order:
for loops
List comprehension
Named Tuples
functions
ZeroDivisionError
Are you looking for something like this :
values=[float(i) for i in input().split()]
print(float(values[0])/float(values[1]))
output:
1 2
0.5
By using a function that does the input for you inside a list comprehension that constructs your 2 numbers:
def inputFloat(text):
inp = input(text) # input as text
try: # exception hadling for convert text to float
f = float(inp) # if someone inputs "Hallo" instead of a number float("Hallo") will
# throw an exception - this try: ... except: handles the exception
# by wrinting a message and calling inputFloat(text) again until a
# valid input was inputted which is then returned to the list comp
return f # we got a float, return it
except:
print("not a number!") # doofus maximus user ;) let him try again
return inputFloat(text) # recurse to get it again
The rest is from your code, changed is the list comp to handle the message and input-creation:
Name = "john"
Place = "Colorado"
print (("Hello %s What's up? \nare you coming to the party tonight in %s\n"+
" if not at least try to make simple calculator:") % (Name, Place))
print ("you will input 2 numbers now and i will devide them for you:")
# this list comprehension constructs a float list with a single message for ech input
calc = [inputFloat("number " + str(x+1)+":") for x in range(2)]
if (calc[1]): # 0 and empty list/sets/dicts/etc are considered False by default
print (float(calc[0])/float(calc[1]))
else:
print ("Unable to divide through 0")
Output:
"
Hello john What's up?
are you coming to the party tonight in Colorado
if not at least try to make simple calculator:
you will input 2 numbers now and i will devide them for you:
number 1:23456dsfg
not a number!
number 1:hrfgb
not a number!
number 1:3245
number 2:sfdhgsrth
not a number!
number 2:dfg
not a number!
number 2:5
649.0
"
Links:
try: ... except:
Lists & comprehensions