difference between " , " and " + " in python - python-3.5

I was having a problem with some code I was writing. I kept getting the error:
input expected at most 1 arguments, got 3
I found the cause of it on http://stackoverflow.com/questions/9969844/error-input-expected-at-most-1-argument-got-3. I am going to refer to the code in a stackoverflow links question because it is easier to read.
def input_scores():
scores = []
y = 1
for num in range(5):
score = int(input('Please enter your score for test', y,': '))
while score < 0 or score > 100:
print ('Error --- all test scores must be between 0 and 100 points')
score = int(input('Please try again: '))
scores.append(score)
y += 1
return scores
If you replace
score = int(input('Please enter your score for test', y,': ')) with
score = int(input('Please enter your score for test ' + str(y) + ': '))
it solves the issue.
My question is why can't you use , instead of +. I have tried looking online but couldn't find an answer for this specific problem

When you use the commas you're saying run the input function with 3 arguments: 'Please enter your score...', y, and ': ' but because input only expects one argument the function outputs an error stating it was expecting 1 argument when you gave it 3.
When you use pluses you're instead running input with 1 argument the string 'Please enter your score...' + str(y) + ': '. The pluses add all of the strings together into one string that then gets fed to input.

Related

Beginner coder. Trying to convert string to integer in Python 3.X [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 3 months ago.
I am a at the very beginning of learning to code in python and am following a tutorial. I attempted to convert this string into an integer to get it to simply add 5 and 6. Here is what I have
No matter what I do, I get 5+6 = 56. Here is what I have:
first_num = (input('Please enter a number '))
second_num = (input('Please enter another number '))
print int((first_num) + int(second_num))
I tried using a comma instead of a plus sign, as a few places suggested. I also tried using int in front of the input line to convert the inputs themselves from strings to integer.
I expect it to add 5 + 6 = 11. I keep getting 56.
I'm not positive what version of Python I'm using, but I know I'm using VS Code and it is Python 3.X. i just don't know what the X is. Here is a screenshot
edit: I have resolved this question. I was not saving the file before I ran it. Therefore every time I tried to change something it was just running the saved, incorrect file. Thanks to those that tried to help me.
In Python when you add two strings together you concatenate the values.
For an easier example:
string_one = "hello"
string_two = " "
string_three = "there"
final = string_one + string_two + string_3
print(final) # hello there
To add them together mathematically, you need to ensure the values are ints, floats, decimals...
one = 1
two = 2
final = one + two
print(final, type(final)) # 3 int
So for your code:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
final = first_num + second_num
print(final) # will give you the numbers added
However, you are casting to ints based on user input, so I would ensure you are also catching the errors that occur when a user enters a value that cannot be cast to an int, like hi. For example:
try:
first_num = int(input('Please enter a number'))
second_num = int(input('Please enter another number'))
print(first_num + second_num) # will give you the numbers added, if ints
except ValueError as ex:
# if any input val is not an int, this will hit
print("Error, not an int", ex)
Try this
first_num = int(input('Please enter a number '))
second_num = int(input('Please enter another number '))
sum=first_num+second_num
print (sum)

Finding the product of user input lines

Using Python 3.6.2 - Completely new to programming, and I need to find the product, sum, and average of user input. I have the sum and average down, but I can't seem to get the product to function right. This is what I have so far...
#Request input from user
sum = 0
while True:
try:
numVar = int(input("Specify number of variables to be entered: "))
break
except ValueError:
pass
while True:
try:
raw = input("Enter a number or press enter for results: ")
break
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
numbers = int(raw)
sum += numbers
ave = round(sum / numVar, 1)
prd = 1
for count in range(numbers):
count = count + 1
prd *= count
#Print results
print("The sum is" , sum)
print("The average is", ave)
print ("The product is", prd)
Any help would be great!
You already got the sum, and you can calculate the product the same way you get the sum.
Changing your code as little as possible, but note that we need to change the variable name sum to instead something like total because sum overwrites the built-in python keyword sum function.
Also, I remove the duplicate line where you take user input: raw = input("Enter a number or press enter for results: ") which was losing the user input:
#Request input from user
total = 0
prd = 1
raw = 0
try:
numVar = int(input("Specify number of variables to be entered: "))
except ValueError:
pass
while raw != "":
raw = input("Enter a number or press enter for results: ")
try:
total += int(raw)
prd *= int(raw)
except ValueError:
pass
ave = round(total / numVar, 1)
print("The sum is" , total)
print("The average is", ave)
print ("The product is", prd)
Demo:
Specify number of variables to be entered: 4
Enter a number or press enter for results: 3
Enter a number or press enter for results: 4
Enter a number or press enter for results: 5
Enter a number or press enter for results: 6
Enter a number or press enter for results:
The sum is 18
The average is 4.5
The product is 360
I hope this helps.

How to do a backspace in python

I'm trying to figure out how to print a one line string while using a for loop. If there are other ways that you know of, I would appreciate the help. Thank you. Also, try edit off my code!
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
for e in range(1,times+1):
print(e)
if e != times:
print("+")
else:
pass
Out:
Enter a number: 5
*
**
***
****
*****
Equation:
1
+
2
+
3
+
4
+
5
How do I make the equation in just one single line like this:
1+2+3+4+5
I don't think you can do a "backspace" after you've printed. At least erasing from the terminal isn't going to be done very easily. But you can build the string before you print it:
times = int(input("Enter a number: "))
print(times)
a = 0
for i in range(times+1):
print("*"*i)
a += i
print("Total stars: ")
print(a)
print("Equation: ")
equation_string = ""
for e in range(1,times+1):
equation_string += str(e)
if e != times:
equation_string += "+"
else:
pass
print(equation_string)
Basically, what happens is you store the temporary equation in equation_str so it's built like this:
1
1+
1+2
1+2+
...
And then you print equation_str once it's completely built. The output of the modified program is this
Enter a number: 5
5
*
**
***
****
*****
Total stars:
15
Equation:
1+2+3+4+5
Feel free to post a comment if anything is unclear.
Instead of your original for loop to print each number, try this:
output = '+'.join([str(i) for i in range(1, times + 1)])
print(output)
Explanation:
[str(i) for i in range(1, times + 1)] is a list comprehension that returns a list of all your numbers, converted to strings so that we can print them.
'+'.join(...) joins each element of your list, with a + in between each element.
Alternatively:
If you want a simple modification to your original code, you can simply suppress the newline from each print statement with the keyword paramater end, and set this to an empty string:
print(e, end='')
(Note that I am addressed the implied question, not the 'how do I do a backspace' question)
Too long for a comment, so I will post here.
The formatting options of python can come into good use, if you have a sequence you wish to format and print.
Consider the following...
>>> num = 5 # number of numbers to generate
>>> n = num-1 # one less used in generating format string
>>> times = [i for i in range(1,num+1)] # generate your numbers
>>> ("{}+"*n + "{}=").format(*times) # format your outputs
'1+2+3+4+5='
So although this doesn't answer your question, you can see that list comprehensions can be brought into play to generate your list of values, which can then be used in the format generation. The format string can also be produced with a l.c. but it gets pretty messy when you want to incorporate string elements like the + and = as shown in the above example.
I think you are looking for the end parameter for the print function - i.e. print(e, end='') which prints each value of e as it arrives followed by no space or newline.

How to get my Python program to pass an online grading system?

Question:
The hand is displayed.
The user may input a word or a single period (the string ".")
to indicate they're done playing
Invalid words are rejected, and a message is displayed asking
the user to choose another word until they enter a valid word or "."
When a valid word is entered, it uses up letters from the hand.
After every valid word: the score for that word is displayed,
the remaining letters in the hand are displayed, and the user
is asked to input another word.
The sum of the word scores is displayed when the hand finishes.
The hand finishes when there are no more unused letters or the user inputs a "."
hand: dictionary (string -> int)
wordList: list of lowercase strings
I am trying to write a code for my Python programming online course. However, I am getting an error :
ERROR: Failed to display hand correctly - be sure 'Current Hand' and the display of the hand are on the same line!
Here is my code :
def playHand(hand, wordList, n):
total = 0
while True:
print("\nCurrent Hand:",)
displayHand(hand)
entered = input('Enter word, or a "." to indicate that you are finished: ')
if entered == '.':
print ("Goodbye! Total score: " + str(total) +" points.")
break
if isValidWord(entered, hand, wordList) == False:
print ("Invalid word, please try again.")
else:
total += getWordScore(entered, n)
print (str(entered), "earned", getWordScore(entered,n), "points. Total:", str(total))
hand = updateHand(hand, entered)
if calculateHandlen(hand) == 0:
print ("\nRun out of letters. Total score: " + str(total) +" points.")
break
The answer is in your code already:
def displayHand(hand):
for letter in hand.keys():
for j in range(hand[letter]):
print(letter,end=" ") # print all on the same line
print() # print an empty line
Use end=" " in your print statement!!

Printing specific parts of a function for Python

I am currently learning to program in python. I am trying to build a basic program that will output how many of each type of coin (quarter, nickel, dime, penny) based off of what number the user inputs. I currently have it so that it will print a 0. However, I'd like it to omit those values in the print statement. I'm not sure how to do that without making each of the different total values and having them print each off of an if statement.
#for if statement and to ask for what coin number it is
y = 1
#asks user for how many coins
x = int(input("How much change are you trying to give (in cents)? "))
while(y <= 1):
q = 25
d = 10
n = 5
p = 1
#Take total and divide by 25 as many times as you can output as quarter
totalq = x // 25
#Take total from that and divide by 10 as many times as you can and output as dime
totald = (x-(q*(totalq))) // 10
#Take total from above and divide by 5 as many times as you can and output as nickel
totaln = (x-(q*(totalq))-(d*(totald))) //5
#Finally take total from above and see how many is left over and output as penny
totalp = (x-(q*(totalq))-(d*(totald))-(n*(totaln))) // 1
y = y + 1
total = (str(totalq) +" quarters " + str(totald) +" dimes " + str(totaln) +" nickels " + str(totalp) + " pennies")
print(total)
I think the most straightforward way to approach this is, as you suggest, using a bunch of ifs - something like:
if totalq:
print(totalq, "quarters", end=' ')
if totald:
print(totalq, "dimes", end=' ')
if totaln:
print(totalq, "nickels", end=' ')
if totalp:
print(totalq, "pennies")
Or, you could make this a little less repetitive using a generator expression:
pairs = [(totalq, 'quarters'),
(totald, 'dimes'),
(totaln, 'nickels'),
(totalp, 'pennies')]
total = ' '.join(str(value) + ' ' + name
for value, name in pairs
if value)
print(total)
Personally, I think the latter approach is prettier, but it's also a bit more complicated. If there's something about this latter code you don't understand, let me know.

Resources