I'm trying to learn python, so I'm just writing some simple programs. I wrote these two bits of code to define two of the functions I want to use in the program, and they both do what they want but when I try to paste them into IDLE it says there is a syntax error at the second def. Any idea what this is?
here's the code:
def print_seq1(number):
number = input("Pick a number: ")
print " "
while number != 1:
if number%2==0:
print number
number = number/2
else:
print number
number = number*3 + 1
print number
print " "
choice = 0
def print_seq2(number):
number = input("Pick a number: ")
print " "
while number != 1:
if number%2==0:
print number,
number = number/2
else:
print number,
number = number*3 + 1
print number
print " "
choice = 0
Interactive interpreters (a.k.a. REPL, just "interpreter", and many other terms) usually expect only a single top-level statement (a function definition, a class definition, a global assignment, a loop, ...) at a time. You give it two and it's confused. Try putting in the first def, a blank line to confirm and actually run your input, then the second def.
When you paste, you mess up the formatting of the code, either re-indent correctly after pasting or paste functions seperately.
Related
I am trying to shorten the process of making lists through the use of a defined function where the variable is the list name. When run, the code skips the user input.
When I run my code, the section of user input seems to be completely skipped over and as such it just prints an empty list. I've tried messing around with the variable names and defining things at different points in the code. Am I missing a general rule of Python or is there an obvious error in my code I'm missing?
def list_creation(list_name):
list_name = []
num = 0
while num != "end":
return(list_name)
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
list_creation(list_Alpha)
print("This is the first list: " + str(list_Alpha))
list_creation(list_Beta)
print("This is the second list: " + str(list_Beta))
I want the two seperate lists to print out the numbers that the user has input. Currently it just prints out two empty lists.
You need to move the return statement to the end of the function, because return always stops function execution.
Also, what you're trying to do (to my knowledge) is not possible or practical. You can't assign a variable by making it an argument in a function, you instead should remove the parameter list_name altogether since you immediately reassign it anyway, and call it like list_alpha = list_creation()
As a side note, the user probably wants to see the whole "To end, type end as number input" bit before they start giving input.
Dynamically defining your variable names is ill advised. With that being said, the following code should do the trick. The problem consisted of a misplaced return statement and confusion of variable name with the variable itself.
def list_creation(list_name):
g[list_name] = []
num = 0
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
g[list_name].append(num)
g = globals()
list_creation('list_Alpha')
print("This is the first list: " + str(list_Alpha))
list_creation('list_Beta')
print("This is the second list: " + str(list_Beta))
There are a couple of fundamental flaws in your code.
You redefine list_name which is what Alpha and Beta lists are using as the return.(list_name = [] disassociates it with Alpha and Beta so your function becomes useless.)
You return from the function right after starting your while loop(so you will never reach the input)
In your function:
list_Alpha = []
list_Beta = []
def list_creation(list_name):
# list_name = [] <-- is no longer Alpha or Beta, get rid of this!
num = 0
...
The return should go at the end of the while loop in order to reach your input:
while num != "end":
num = input("Input a number: ")
print("To end, type end as number input")
if num != "end":
list_name.append(num)
return(list_name)
I'm trying to make a program in Python 3.5 that asks the user to enter a number from 1 to 9. The the program will also guess a number from 1 to 9. If the user guesses the same number correctly, then the program will print Correct . Otherwise, the program will print Wrong. I wrote a program. Everything went fine with my code. However, when I guessed a number correctly, the program suddenly wrote Wrong instead of Correct. What am I doing wrong?
Here is my code:
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
import random
random = print(random.randint(1,9))
if int(x) != random:
print ('Wrong')
else:
print ('Correct')
You are saving the result of a print() call (and masking random). print() returns None, so it will always be unequal to an integer, and therefore always "wrong."
import random
print('Enter a number from 1 to 9')
x = int(input('Enter a number: '))
r = random.randint(1,9)
if x != r:
print('Wrong')
else:
print('Correct')
Also note that I've moved the import statement to the top, avoided a second int() cast on something you've already done that to, and removed the space between the print reference and its arguments.
Here is the mistake,
random = print(random.randint(1,9))
You need to do something like this.
random = random.randint(1,9)
print(random)
Also, you have already converted the input to int so, you can do just this.
if x != random:
As pointed out your mistake is the line
random = print(random.randint(1,9))
But why?
functions (like print() take something, do something (with it) and give something back.
Example:
sum(3,4) takes 3 and 4, may add them and returns 7.
print("Hello World") on the other hand takes "Hello world", prints it on the screen but has nothing useful to give back, and therefore returns None (Pythons way to say "nothing").
You then assign None to the name random and test if it equals your number, which it (of course) doesn't.
first_num = raw input ("Please input first number. ")
sec_num = raw input (" Please input second number:")
answer = into( first_num) +into( sec_num)
print " Now I will add your two numbers : ", answer
print " Pretty cool. huh ?
print " Now I'll count backwards from ",answer
counter = answer
while (counter >=0):
print counter
counter = counter-1
print " All done !"
I think the first half in a command to add first and second numbers to get sum and the second half is a command to return to start or zero out. I don't know python language.
You should probably try to run the code first and play with it to understand it. The code is simple; the first half take two user inputs and add them to each other then it displays the result.
first_num = input("Please input first number:") # get first number input
sec_num = input("Please input second number:") # get second number input
answer = int(first_num) +int(sec_num) # add up int values of the numbers
print(" Now I will add your two numbers : ", answer) # display answer
As for the second half it takes a number from which it counters downward till zero
print("Now I'll count backwards from ", answer)
counter = answer # set counter start value
while(counter >=0):
print(counter) # display counter value on each iteration
counter = counter-1 # decrement counter value on each iteration
print(" All done !)
I changed your code cause your lines were a bit messy and some incorrect. This version by me works on python3 and NOT python2.7. If you want to learn python I advise you to start with code academy python tutorial
My teacher requests me to make a calculator that can calculate a 15% tip on a submitted price. I followed an online tutorial for this python application. I made a simple addition, subtraction, multiplication, and division calculator for practice before I make what my teacher requires. In the YouTube video I followed the python application ran on his computer. I get a a "Invalid Syntax" error in the Python Shell. I'm using Python 3.3.0. Thank you.
EDIT: I followed a different tutorial figured out how to finish my project. The only problem I'm having is using both regular integers (1, 2, 3, 4, etc.) and float integers (4.36, 5.45, etc.).
print("Welcome to the calculator!")
mealPrice = int(input("Enter your meal price:"))
asw = mealPrice * 0.15
print("The tip you owe is: ", asw)
because y is string
y = int(raw_input("Input second integer: "))
I see a couple problems with your code.
Your use of print on the first line will give you troubles, because print is a function in Python 3. You should call it like print("hello").
On line 8, you have an extra colon:
calc():
Get rid of that.
Last, you don't need the semicolons when you call calc()
This has a lot of changes to do.
First, the first line of code should be:
print ("Hello")
Then, the raw_input() should become input().
Next, there should not be a colon or semicolon after calc() except on the second line when you are defining a function.
The code should look something like this. Try it.
print ("Hello")
def calc():
x = int(input("Input first integer: "))
y = int(input("Input second integer: "))
type = str.lower(input("(A)dd, (S)ubstract, (M)ultiply, (D)ivide \n"))
if type != "a" and type != "s" and type != "m" and type != "d":
print ("Sorry, the command you entered is not valid.")
calc()
else:
if type =="a":
print ("The result is '" + str(x+y) + "'")
elif type == "s":
print ("The result is '" + str(x-y) + "'")
elif type =="m":
print ("The result is '" + str(x*y) + "'")
elif type == "d":
print ("The result is '" + str(float(x)/float(y)) + "'")
if int(input("Enter 1 if you would like to perform another calculation? \n")) == 1:
calc()
else:
exit()
calc()
Hope this helps.
Instead of converting to int (thus flooring whatever your value is -- 2.99 becomes 2, for instance) converting to float should do the trick nicely; the tip calculation should work even if you're doing 2.0*0.15 instead of 2*0.15.
This will obviously only work when you know what input you can expect. It will fail pretty badly if someone enters anything that isn't valid.
If you want to use integer:
mealprice = int(input("Enter your meal price:"))
If you want to use float:
mealprice = float(input("Enter your meal price:"))
Float is recommended because You can also use a single number like 1,2,3 etc and also float numbers.
I also created my own calculator that has 6 functions:
1 = Add
2 = Subtract
3 = Multiply
4 = Divide
5 = Round Off
6 = Get Remainder
It is so simple.
I have Not Used Round Off yet.
If You want That code Ask me I will give you.
If you want more Info, I am ready to Provide To you.
I figured it out. I was supposed to use:
int(float(input("Enter your meal price:")))
Thank you, everyone!
I need to write a prog in Python that accomplishes the following:
Prompt for and accept the input of a number, either positive or negative.
Using a single alternative "decision" structure print a message only if the number is positive.
It's extremely simply, but I'm new to Python so I have trouble with even the most simple things. The program asks for a user to input a number. If the number is positive it will display a message. If the number is negative it will display nothing.
num = raw_input ("Please enter a number.")
if num >= 0 print "The number you entered is " + num
else:
return num
I'm using Wing IDE
I get the error "if num >= 0 print "The number you entered is " + num"
How do I return to start if the number entered is negative?
What am I doing wrong?
Try this:
def getNumFromUser():
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
else:
getNumFromUser()
getNumFromUser()
The reason you received an error is because you omitted a colon after the condition of your if-statement. To be able to return to the start of the process if the number if negative, I put the code inside a function which calls itself if the if condition is not satisfied. You could also easily use a while loop.
while True:
num = input("Please enter a number: ")
if num >= 0:
print "The number you entered is " + str(num)
break
Try this:
inputnum = raw_input ("Please enter a number.")
num = int(inputnum)
if num >= 0:
print("The number you entered is " + str(num))
you don't need the else part just because the code is not inside a method/function.
I agree with the other comment - as a beginner you may want to change your IDE to one that will be of more help to you (especially with such easy to fix syntax related errors)
(I was pretty sure, that print should be on a new line and intended, but... I was wrong.)