E.g "input("what is",a,b,c,"?")"
However this doesn't work
a is a random number
b is a + sign
c is another random number
When i try and run the code it says:
:TypeError: input expected at most 1 arguments, got 5
p.s im am new to coding so please use simple language so that i can understand
I think your issue is a fundamental misunderstanding of how input works. It's really difficult to parse out what you're trying to do with the input, but I'll give it a shot.
The 'input' function asks the user for exactly that, input. It will then store that input somehow. Usually you'll want to assign it to a variable, as in:
inputString = input('What is a, b, c')
From there, you could apply formatting to inputString, and then assign that to variables as well. Reading the official documentation, as well as doing a cursory search for the '.split()' method will likely give you what you're looking for.
This existing SO question may also yield some helpful information for you
In my experience, Google is your absolute best friend, especially when starting out. I'm not here to flame you and put you down, but the majority of SO users will expect you to exhaust all your personal resources and do at least the minimum amount of basic research before posting here. All I looked for to get to the linked post was "getting multiple variables from user input python" in Google. Taking care of this beforehand will save you a lot of negative votes, and generally yield more helpful, positive experiences here.
Edit: It should be noted that a lot of what I covered in the last paragraph is clearly outlined in the rules of the site. Not following them will have negative repercussions outside of the dislike of your peers.
You need to provide a single string argument when calling input, i.e. input("enter input now"). If b is always a +, try input("what is {}+{}".format(a,c)). The first argument in format will replace the first {} in the string, the second argument in format will replace the second {} in the string, and so on.
import numpy as np
a= np.random.randint(0,10)
b = "+"
c = np.random.randint(0,10)
print("what is 'a,b,c'", eval(str(a)+str(b)+str(c)))
If you want to input a random number and assign it to a and b. You should use following:
a = input("Value of a?\n")
b = input("Value of b?\n")
Related
I'm currently doing a dice game for my school programming project, and it includes the rules: 'Stores the winner’s score, and their name, in an external file' and 'Displays the score and player name of the top 5 winning scores from the external file.' I've done everything in my game apart from the leaderboard. I am able to write the name and score of the user into the txt file, but I am unsure of how to then sort it, and would also like when people first start the program can use the menu to go to the leaderboard where it would then read the txt file and print the top 5 scores in order including the names.
I've checked loads of over questions similar to mine, but none of them exactly worked for my code as I kept on getting errors implementing other people's code into mine which just weren't compatible with my layout.
(deleted)
Thanks in advance, I've never used stack overflow to ask a question so I apologize if there's anything I've done wrong in my post.
You did good on the question. You stated the problem clearly and, most importantly, you added enough code to run the code so we can have a look at how the program behaves and what's going wrong. In this case nothing is going wrong which is good :)
Considering you mention that this is a school project I will not give you a fully copy/paste solution but will explain hopefully enough details on how to solve this on your own.
Now according to the question, you don't know how to sort your leaderboard. I ran the program a few times myself (after removing the sleeps because I am impatient 😋) and see that your leaderboard file looks like this:
90 - somename
38 - anothername
48 - yetanothername
To display this you must do two things:
Open the file and read the data
Convert the data from the file into something usable by the program
The first step seems to be something you already know as you already use open() to write into the file. Reading is very similar.
The next step is not so obvious if you are new to programming. The file is read as text-data, and you need to sort it by numbers. For a computer the text "10" is not the same a the number 10 (note the quotes). You can try this by opening a Python shell:
>>> 10 == 10
True
>>> 10 == "10"
False
>>> "10" == 10
False
And text sorts differently to numbers. So you one piece of the solution is to convert the text into numbers.
You will also get the data as lines (either using readlines() or splitlines() depending on how you use it. These line need to be split into score and name. The pattern in the file is this:
<score> - <name>
It is important to notice that you have the text " - " as separator between the two (including spaces). Have a look at the Python functions str.split() and str.partition(). These functions can be applied to any text value:
>>> "hello.world".split(".")
['hello', 'world']
>>> "hello.world".partition(".")
('hello', '.', 'world')
You can use this to "cut" the line into multiple pieces.
After doing that you have to remember the previous point about converting text to numbers.
As a last step you will need to sort the values.
When reading from the file, you can load the converted data into a Python list, which can then be sorted.
A convenient solution is to create a list where each element of that list is a tuple with the fields (score, name). Like that you can directly sort the list without any arcane tricks.
And finally, after sorting it, you can print it to the screen.
In summary
Open the file
Read the data from the file as "lines"
Create a new, empty list.
Loop over each line and...
... split the line into multiple parts to get at the score and name separately
... convert the score into a number
... append the two values to the new list from point 3
Sort the list from point 3
Print out the list.
Some general thoughts
You can improve and simplify the code by using more functions
You already show that you know how to use functions. But look at the comments #THIS IS ROUND1 to #THIS IS ROUND5. The lines of code for each round are the same. By moving those lines into a function you will save a lot of code. And that has two benefits: You will only need to make a code-change (improvement or fix) in one place. And secondly, you guarantee that all blocks behave the same.
To do this, you need to think about what variables that block needs (those will be the new function arguments) and what the result will be (that will be the function return value).
A simple example with duplication:
print("round 1")
outcomes = []
value1 = random(1, 100)
value2 = random(1, 100)
if value1 > value2:
outcomes.append("A")
else:
outcomes.append("B")
print("round 2")
outcome = ""
value1 = random(1, 100)
value2 = random(1, 100)
if value1 > value2:
outcomes.append("A")
else:
outcomes.append("B")
Rewritten with functions
def run_round(round_name):
print(round_name)
value1 = random(1, 100)
value2 = random(1, 100)
if value1 > value2:
return "A"
else:
return "B"
outcomes = []
result_1 = run_round("round 1")
outcomes.append(result_1)
result_2 = run_round("round 2")
outcomes.append(result_2)
As you can see, the second code is much shorter and has no more duplication. Your code will have more function arguments. It is generally a challenge in programming to organise your code in such a way that functions have few arguments and no complex return values. Although, as long as it works nobody will look too closely ;)
Safe way to ask for a password
You can use getpass() from the module getpass() to prompt for a password in a secure manner:
from getpass import getpass
password = getpass()
Note however, if you are using PyCharm, this causes some issues which are out of scope of this post. In that case, stick with input().
Sleeps
The "sleep()" calls are nice and give you the chance to follow the program, but make it slow to test the program. Consider to use smaller values (comma-values are possible), or, even better, write your own function that you can "short-circuit" for testing. Something like this:
import time
ENABLE_SLEEP = True
def sleep(s):
if ENABLE_SLEEP:
time.sleep(s)
print("some code")
sleep(1)
print("more code")
sleep(4)
You will then use your own sleep() function anytime you want to wait. That way, you can simply set the variable ENABLE_SLEEP to False and your code will run fast (for testing).
I hope this question does not get closed/downvoted, as it really takes a good portion of the time I spend coding.
As a developer more focused on Python, I try to follow PEP8 standard, but for some variable names it becomes really tricky to me.
Let's say the word TEMPERATURE.
If I want to have a variable to store a list of temperatures, I would name it:
temperature_list = []
However, as the code gets more complex, let's say I have to call a function with the temperature_list as an argument:
calling_function(variable_with_long_name, temperature_list, another_long_name_variable)
You can clearly see where it leads...
So I decide to rename temperature_list to temp_list. Which can sound as a good choice, right?
Except...
If I also want to store TEMPORARY FILES in a list, I may occur to have:
temp_list = []
temp_file_list = []
It may come to the point where my variables start messing around and turning the code a bit tricky to follow.
What is the convention and what other actions do programmers do when face such situation? Is there any reference to follow for such cases, like a casebook of good variable names for certain nouns?
-- edit
If you vote for closing it, at least explain why! --'
Usually, you are required to find clever names, that are not too long, but explains the variable properly. When this fails, or there are too many variables doing similar work (so would have close names), you can choose to explain the variables in a docstring or a comment, and give short names (still meaningful names, not a, b, etc...)
def function(a, b):
"""
l_variable used for bla bla,
lo_variable is good for bla bla.
"""
l_variable = 12
lo_variable = 123
lon_variable = 1234 # This is an integer bla bla
When you really have the need for long variable names, where I sometimes cannot avoid myself, I try to lower line lengths while not breaking the purpose of the code. For example breaking lines in function calls(like in your example).
def f(a, b, c):
print a + b + c
this_is_a_long_variable_name = "Stack"
this_is_an_even_longer_variable_name = "Over"
this_is_the_longest_variable_name_in_this_example = "flow"
f(this_is_a_long_variable_name,
this_is_an_even_longer_variable_name,
this_is_the_longest_variable_name_in_this_example)
I feel like there is a simple solution to this but I am kinda new.
stat_input= input("Hello Mr. Jenner, what are you interested in tracking today?")
I use an input like this which later is used to call upon data and uses that data to calculate statistics and produce histogram charts / normal distributions.
It works quite nicely. Here are some examples where it is used.
cur.execute('SELECT {} FROM statdata'.format(stat_input))
np.array(stat_input).astype(np.float)
sigma = math.sqrt(np.var(stat_input))
So if I type threemonthdata it will pull the array of data from my database and use it . Its great. However, I have one small problem
I understand that threemonthdata refers to an array. Since I am creating charts, I want to use the input as the title so the chart title identifies what data I am drawing and using (as a reference in the future)
ax.set_title('stat_input')
This doesn't work
ax.set_title(' + stat_input + ')
Nor does this. I want the title to say Threemonthdata. But if I input twomonthdata I want it to say twomonthdata and not give me the array of numbers.
Any ideas?
I have never played with psycopg's cursor class. But, from what I can read, it appears that this one does the job for you of turning your string in place into a list whose name is the same as the referring string.
Thus what about defining another viariable to store the string before it is overriden ? As follows
stat_input_title = stat_input.capitalize()
cur.execute('SELECT {} FROM statdata'.format(stat_input))
Henceforth, stat_input_title and stat_input can be used together withouh conflicting.
ax.set_title(stat_input_title)
It looks like the issue you are facing is that you are passing the set_title() a string 'stat_input', and not the variable stat_input. You likely simply need to use:
ax.set_title(stat_input)
I wonder if you can help because I've been looking at this for a good half hour and I'm completely baffled, I think I must be missing something so I hope you can shed some light on this.
In this area of my program I am coding a query which will search a list of tuples for the salary of the person. Each tuple in the list is a separate record of a persons details, hence I have used two indexes; one for the record which is looped over, and one for the salary of the employee. What I am aiming for is for the program to ask you a minimum and maximum salary and for the program to print the names of the employees who are in that salary range.
It all seemed to work fine, until I realised that when entering in the value '100000' as a maximum value the query would output nothing. Completely baffled I tried entering in '999999' which then worked and all records were print. The only thing that I can think of is that the program is ignoring the extra digit, which I could not figure out why this would be?!
Below is my code for that specific section and output for a maximum value of 999999 (I would prefer not to paste the whole program as this is for a coursework project and I want to prevent anyone on the same course potentially copying my work, sorry if this makes my question unclear!):
The maximum salary out of all the records is 55000, hence why it doesnt make sense that a minimum of 0 and maximum of 100000 does not work, but a maximum of 999999 does!
If any more information is need to help, please ask! This probably seems unclear but like I said above, I dont want anyone from the class to plagiarise and my work to be void because of that! So I have tried to ask this without posting all my code on here!
Given your use of the print function (instead of the Python 2 print statement), it looks like you're writing Python 3 code. In Python 3, input returns a str. I'm guessing your data is also storing the salaries as str (otherwise the comparison would raise a TypeError). You need to convert both stored values and the result of input to int so it performs numerical comparisons, not ASCIIbetical comparisons.
When you read in from standard input in Python, no matter what input you get, you receive the input as a string. That means that your comparison function is resulting to:
if tuplist[x][2] > "0" and tuplist[x][2] < "999999" :
Can you see what the problem is now? Because it's a homework assignment, I don't want to give you the answer straight away.
How do I trim the output of Python Pyenchat Module's 'suggested words list ?
Quite often it gives me a huge list of 20 suggested words that looks awkward when displayed on the screen and also has a tendency to go out of the screen .
Like sentinel, I'm not sure if the problem you're having is specific to pyenchant or a python-familiarity issue. If I assume the latter, you could simply select the number of values you'd like as part of your program. In simple form, this could be as easy as:
suggestion_list = pyenchant_function(document_filled_with_typos)
number_of_suggestions = len(suggestion_list)
MAX_SUGGESTIONS = 3 # you choose what you like
if number_of_suggestions > MAX_SUGGESTIONS:
answer = suggestion_list[0:(MAX_Suggestions-1)] # python lists are indexed to 0
else:
answer = suggestion_list
Note: I'm choosing to be clear rather than concise here, since I'm guessing that will be valued by asker, if asker is unclear on using list indices.
Hope this helps and good luck with python.
Assuming it returns a standard Python list, you use standard Python slicing syntax. E.g. suggestedwords[:10] gets just the first 10.