I'm having trouble with the extra credit on Exercise 13 of Learn Python the Hard Way.
It wants me to combine argv with raw_input, which I can't figure out.
Could anyone help me out? Examples would be great!
Thanks so much!
Edit: The original code for the exercise is:
from sys import argv
script, first, second, third = argv
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
an example would be indistinguishable from the answer, which is unlikely to be the best way to help you. perhaps you are overthinking the question, though. i believe the idea is to use some command-line input (which goes into argv) and some entered input (which comes through raw_input) to make a script which reports on both. For example, it might produce:
The script is called: ex13.py
Your first variable is: cheese
Your second variable is: apples
You entered the following data: foo bar baz
This is how I tried to do it:
from sys import argv
script, weather, feeling = argv
print "Hot or Cold",
weather = raw_input()
print "Happy or sad",
feeling = raw_input()
print "The name of the script is:" , script
print "The day is:", weather
print "Today I am feeling:", feeling
import sys
def main():
all_args = sys.argv[:]
user = None
while user != 'STOP':
user = raw_input('You have %d args stored. Enter STOP or add another: ' % len(all_args))
if user != 'STOP':
all_args.append(user)
print 'You entered %d args at the command line + %d args through raw_input: [%s]' % (len(sys.argv), len(all_args) - len(sys.argv), ', '.join(all_args))
if __name__ == '__main__':
main()
This was confusing to me as well. The author puts this in his faq at the bottom.
Q: I can't combine argv with raw_input().
A: Don't overthink it. Just slap two lines at the end of this script that uses raw_input() to get something and then print it. From that start playing with more ways to use both in the same script.
Here is how I solved this: (note: you still have to provide the arguments when initially running the script)
from sys import argv
script, first, second, third = (argv)
print "The script is called:", script
print "Your first variable is:", first
print "Your second variable is:", second
print "Your third variable is:", third
first = raw_input("\nNew First Variable? ")
second = raw_input("New Second Variable? ")
third = raw_input("New Last Variable? ")
print "\n\nYour new variables are %s, %s, and %s" % (first, second, third)
Here's the output I get:
C:\Users\mbowyer\Documents\Python_Work>python ex13a.py 1 2 3
The script is called: ex13a.py
Your first variable is: 1
Your second variable is: 2
Your third variable is: 3
New First Variable? a
New Second Variable? b
New Last Variable? c
Your new variables are a, b, and c
C:\Users\mbowyer\Documents\Python_Work>
Related
def main():
name = ''.join(user_word.lower().split())
name = name.replace('-','') # what?
limit = len(name)
phrase = True
while running:
temp_phrase = phrase.replace(' ', '')
if len(temp_phrase) < limit:
print(f"length of anagram phrase = {len(temp_phrase)}")
find_anagram(name, dict_file)
print("Current anagram phrase =", end = " ")
print(phrase, file=sys.stderr)
choice, name = process_choice(name)
phrase += choice + ' '
elif len(temp_phrase) == limit:
print("\n**FINISHED!!**\n")
print("Anagram of name", end = " ")
print(phrase, file=sys.stderr)
print()
try_again = input("\n\nWant to try again? (Press Enter or else 'n' to quit)\n")
if try_again.lower() == 'n':
running = False
sys.exit()
else:
main()
after running my code I keep getting the error
UnboundLocalError: local variable 'running' referenced before assignment
so I tried making a variable named running in my main function's argument but I got a different error so I just figure I would try to work out this first. Any clue as to how to fix it.
Side note: this problem is from the book impractical python projects (chapter 3 project 5), I copied almost every bit of code so I'm not sure how it isn't working.
The reason you are getting a variable referenced before assignment error is because, as the error describes, you are referencing a variable before assigning any value to it.
The variable running is only referenced inside the while loop, not before. for this to work, you would have to add a line above your while loop assigning a value to running.
Consider this example:
def my_function():
print(my_variable)
my_variable = 'this is a string'
my_function()
In this example, I attempted to print my_variable. However, there was nothing assigned to it before I tried to print it. So the output is the following:
UnboundLocalError: local variable 'my_variable' referenced before assignment
However, if I assign the variable some value before I print it like this, I get the output I am expecting.
def my_function():
my_variable = 'this is a string'
print(my_variable)
my_function()
Output:
this is a string
You may ask why this happens, shouldn't python be able to see that I assigned a value to it and just print that value? The answer to that question is no. To put it simply, Python is executed from top to bottom, so when there is an attempt to print my_variable without assigning anything to it above, the code crashes. Here is some info on how python code works.
I believe this error means I can't include a variable in a loop however I am struggling to see a way around....
the error is
TypeError: range() integer end argument expected, got unicode.
The problem the book tried to ask me is:
Try wring a program the will prompt for an number and print the correct times table (up to 12).
This is my code:
def main():
pass
choice = raw_input("Which times table would you like")
print ("This is the", choice , "'s times table to 12")
var1 = choice*12 + 1
for loopCounter in range (0,var1,choice):
print(loopCounter)
if __name__ == '__main__':
main()
Any suggestions? thanks in advance.
The raw_input function gives you a string, not an integer. If you want it as an integer (such as if you want to multiply it by twelve or use it in that range call), you need something such as:
choice = int(raw_input("Which times table would you like"))
There are potential issues with this simplistic solution (e.g., what happens when what you enter is not a number), but this should be enough to get past your current problem.
This error just means that it got a unicode value when an integer was assumed.
That happens because you use raw_input for choice.
Edit: raw_input does not interpret your input. input does.
Your program will run with a few changes.
def main():
pass
choice = input("Which times table would you like")
print ("This is the " + choice + "'s times table to 12")
var1 = int(choice)*12 + 1
for loopCounter in range (0,var1,int(choice)):
print(loopCounter)
if __name__ == '__main__':
main()
Now you may want to adjust it more so that you get the correct output, the above will compile and run.
The project is to create a simple Python program that will prompt the user for his or her age and then print out the lower and upper age limits for the user's date based on the Permissible Dating Age Algorithm.
The PDA Algorithm is: d = a/2 + 7, a is your age, and d is the lowest permissible age of your date where a is an integer.
Here is the code I have so far:
import random
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdoutflush()
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
It seems to be running okay, yet nothings printing out and I'm confused as to what's going wrong with the print statements.
You weren't that far off the mark to be honest but your print statements were not faulty. Rather, they are contained within a function that you never call so they never actually run. There is also a small typo. This code will run:
import random #Not needed with current code
import sys
import time
def findACompanion():
print "Welcome to the Permissible Dating Age Program!"
sys.stdout.flush() #You missed a full-stop
time.sleep(3)
a = float(raw_input("What is your age?"))
if a <= 14:
print "You are too young!"
else:
d = a/2 + 7
print "You can date someone"
print d
print "years old."
#Something to call your function and start it off
start_program = findACompanion()
Stick with the classes, it won't take long till it falls into place. Being thrown in at the deep-end is the best way :)
You've defined a function findACompanion, but nothing is calling the function, so none of the statements within the function are being executed. You can call it yourself from the prompt:
>>> findACompanion()
There's a convention that is common in Python to detect if you are running a file as your main program and to make the call automatically, see Top-level script environment. The convention calls for the function to be called main but you can call anything you'd like.
if __name__ == "__main__":
findACompanion()
So I am making a simple randomized number game, and I want to save the players High Score even after the program is shut down and ran again. I want the computer to be able to ask the player their name, search through the database of names in a text file, and pull up their high score. Then if their name is not there, create a name in the database. I am unsure on how to do that. I am a noob programmer and this is my second program. Any help would be appreciated.
Here is the Code for the random number game:
import random
import time
def getscore():
score = 0
return score
print(score)
def main(score):
number = random.randrange(1,5+1)
print("Your score is %s") %(score)
print("Please enter a number between 1 and 5")
user_number = int(raw_input(""))
if user_number == number:
print("Congrats!")
time.sleep(1)
print("Your number was %d, the computers number was also %d!") %(user_number,number)
score = score + 10
main(score)
elif user_number != number:
print("Sorry")
time.sleep(1)
print("Your number was %d, but the computers was %d.") %(user_number, number)
time.sleep(2)
print("Your total score was %d") %(score)
time.sleep(2)
getscore()
score = getscore()
main(score)
main(score)
EDIT:
I am trying this and it seems to be working, except, when I try to replace the string with a variable, it gives an error:
def writehs():
name = raw_input("Please enter your name")
a = open('scores.txt', 'w')
a.write(name: 05)
a.close()
def readhs():
f = open("test.txt", "r")
writehs()
readhs()
with open('out.txt', 'w') as output:
output.write(getscore())
Using with like this is the preferred way to work with files because it automatically handles file closure, even through exceptions.
Also, remember to fix your getscore() method so it doesn't always return 0. If you want it to print the score as well, put the print statement before the return.
In order to write a file using python do the following:
file2write=open("filename",'w')
file2write.write("here goes the data")
file2write.close()
If you want to read or append the file just change 'w' for 'r' or 'a' respectively
First of all you should ask your question clearly enough for others to understand.To add a text into text file you could always use the open built-in function.Do it like this.
>>> a = open('test.txt', 'w')
>>> a.write('theunixdisaster\t 05')
>>> a.close()
Thats all.If need further help try this website.
http://www.afterhoursprogramming.com/tutorial/Python/Writing-to-Files/
You could also use a for loop for the game to print all the scores.
Try this one on your own.It would rather be fun.
THE RECOMENDED WAY
Well as if the recommended way use it like this:
>>> with open('test.txt', 'w') as a:
a.write('theunixdisaster\t 05')
With this its certain that the file would close.
With variables
>>> name = sempron
>>> with open('test.txt', 'w') as a:
a.write('%s: 05' % name)
Now try calling it.Well I use python 3.4.2.So, if you get into errors, try to check if there is any difference in the string formatting with the python version that you use.
Basically I want to record high scores in my program. I'm new to coding so need a bit of help. I will create this basic program to demonstrate what I want.
import time
name = input("Please enter your name: ")
mylist=["Man utd are the best team","I am going to be a pro typer.","Coding is really fun when you can do it."]
x=random.choice (mylist)
print ("The sentence I would like you to type is: ")
print (x)
wait = input ("Please press enter to continue, The timer will start upon hitting enter!")
start = time.time()
sentence = input("Start typing: ")
end = time.time()
overall = end - start
if sentence == (x):
print ("It took you this many seconds to complete the sentence: %s" % overall)
if overall <= 9:
print ("Nice job %s" % name)
print ("You have made it to level 2!")
How would I be able to save the time it took and if someone beats the time make that the new high score?
You're looking for a way to persist data across program executions. There are many ways to do it, but the simplest is just writing to a file.
In addition, if you want to use a database, look into SQLite3 for Python.