using loops for input list by user - python

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

Related

Python Nested List: How to print specific elements and append to each sublist

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)

Error "invalid syntax" appears when trying to redirect using input/output in Python shell

I tried to practice input/output redirection in the Python shell. I have a file named SentinelValue.py which is where I have this code to add up the numbers in another file:
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
sum = 0
while data != 0:
sum += data
data = eval(input("Enter an integer (the input ends " + "if it is 0): "))
print("The sum is", sum)
The other file "Numbers.txt" contains numbers:
1
2
3
4
5
6
7
8
9
0
and my output.txt file is where I want the sum to show.
I tried using:
python SentinelValue.py < Numbers.txt > output.txt
but on shell, it highlights "SentinelValue" & says "invalid syntax".
I don't know why it's not working.
There are several things wrong with your code:
As already suggested in the comments, do not use eval() for a direct user input (or pretty much any time, in 99% cases when you think you need it - you don't!). A simple int() conversion should be more than enough without all the dangers of eval().
Connected with the previous, eval() evaluates the input. Further more, on Python 2.x input() itself does the evaluation (it's an equivalent of eval(raw_input())) so whenever it encounters an invalid input it will pop a SyntaxError.
Even if it doesn't pop a SyntaxError, it will most certainly pop a TypeError as eval() expects a string and it will receive an integer from the inner input().
You're printing the "Enter an integer..." prompt to STDOUT which will result it ending up in your output.txt (where you redirect the STDOUT).
You're shadowing the built-in sum() by using it as one of your variables. That's a bad practice that can lead to many problems and unexpected results down the line.
So, with all that in mind, here's how to rewrite it to address these issues:
# Let's first make sure it works on Python 2.x and 3.x by shadowing the input
try:
input = raw_input # on Python 2.x use raw_input instead of input
except NameError:
pass
result = 0 # tip: use a name that's not already built-in, like result
while True: # loop 'forever'...
data = input() # don't print anything when asking for input
try:
data = int(data) # don't print anything to STDOUT
if not data: # only if the integer is 0
break
result += data # add to the final result
except ValueError: # risen if the input is not an integer...
pass # so just ignore it
print("The sum is: " + str(result)) # finally, print the result

Handling input data quality with checks & default value

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")))

Beginner - Script recognizing "pi" and "e" and converting them into numbers

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 )

Doctor program - python

Below is a short doctor program that I am making and this is the start, unfortunately, it doesn't work. Here is the error I receive -
TypeError: input expected at most 1 arguments, got 4
least = 0
most = 100
while True:
try:
levelofpain = int(input("How much is it hurting on a scale of", (least), "to", (most)))
while llevelofpain < least or levelofpain > most:
print ("Please enter a number from", (least), "to", (most))
levelofpain = int(input("How much is it hurting on a scale of", (least), "to", (most)))
break
except ValueError:
print ("Please enter a number from", (least), "to", (most))
Thanks in advance!
p.s. using python 3.3
The error message is self-explanatory -- you are passing four arguments to input(...) where it is only accepting one.
The fix is to turn the argument into a single string.
levelofpain = int(input(
"How much is it hurting on a scale of {} to {}? ".format(least, most)))
For formatting strings, you probably want to use Python's .format() function. Take a look at this question: String Formatting in Python 3
There are two main methods for formatting strings in Python, the new way using the .format method of the str class, and the old C style method of using the % symbol:
str.format():
"This is a string with the numbers {} and {} and {0}".format(1, 2)
C Style Format (%):
"This is another string with %d %f %d" % (1, 1.5, 2)
I strongly recommend not using the C Style Format, instead use the modern function version. Another way I don't recommend is replacing the input function with your own definition:
old_input = input
def input(*args):
s = ''.join([str(a) for a in args])
return old_input(s)
input("This", "is", 1, 2, 3, "a test: ")

Categories

Resources