I'm learning python for 2 weeks.
So my question is let's say I created a calculator.
How can I add number as much as user likes?
os.system("del *.pyc")
print "Hello %s!" % ad
print "---------------------------------------"
print " *Add"
print " *x Add (Dunno english)"
print " *Multiply"
print " *x Multiply (Look up)"
print " *Multiply by itself"
print " *math.sqrt"
print "---------------------------------------"
print "What u want? :)"
choice = raw_input("Secimim= ")
print "So you choose %s :)" % choice
print ""
print "redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
first=input("First number= ")
second=input("Second= ")
print "Result= " + str(add(first,second))
os.system("pause")
Rest of them is same
Let's make this part english
print "Let's have your choice :)"
secim = raw_input("Secimim= ")
adsiz = (ad,secim)
print "So you selected this :)" % adsiz
print ""
print "Redirecting..."
time.sleep(3)
os.system("cls")
if secim.lower()=="add":
ilksayi=input("IFirst= ")
ikincisayi=input("Second= ")
print "Result= " + str(toplama(ilksayi,ikincisayi))
os.system("pause")
def toplama(x,y):
return x+y
This part
if secim.lower()=="add":
firstnumber=input("IFirst= ")
secondnumber=input("Second= ")
print "Result= " + str(add(ilksayi,ikincisayi))
os.system("pause")
I want to make it like a loop that it says:
Number=10
Number = 26
Number = 62
...
And when you type
Number= (Blank)
It print the result.
Just like the phone's calculators.
I tried making it with loop that breaks when user types quit.
But I can't declare that much variable.
How to make auto making variables?
I think you are looking for something like this.
Python 2
num = '0'
total = 0
while True: #run loop until user enters something that is not a number
if not num.isdigit():
break #at this point break out of the loop
total += int(num) #else add the number to the total (could be / * - +)
num = raw_input('Number:\t')
print total #finally print the total
Or you could use an approach with Lists
nums = []
while True:
num = raw_input('Number: ')
if num.isdigit(): nums.append(int(num))
else: break;
print sum(nums)
Do you mean something like...
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
number = 0
input = raw_input('Number: ')
while input != None and input != "":
if not is_number(input):
print "NaN"
continue
number += float(input)
input = raw_input('Number: ')
print "Number = %s" % (number, )
I typed it blind so there might be errors in the code but you get the drift hopefully
Try this:
#! python3
# coding=utf-8
"""Add a lot of numbers."""
def add_everything():
""" """
numbers = []
while True:
print("Sum:", sum(numbers) )
s = input("Enter number(s) or just hit Return to quit:")
if not s:
break
for n in s.split():
try:
number = float(n)
except ValueError:
print("That wasn't a number. Try again!")
else:
numbers.append( number )
print("added {} to {}".format( number, sum(numbers[:-1]) ) )
finally:
pass
print("That was fun!")
print("I remembered all your {} numbers:".format(len(numbers)) )
for n in numbers:
print(" {:4.2f}".format(n) )
print("--------")
print(" {:4.2f}".format( sum(numbers) ) )
if __name__ == '__main__':
add_everything()
Example:
Sum: 0
Enter number(s) or just hit Return to quit:123 45.6
added 123.0 to 0
added 45.6 to 123.0
Sum: 168.6
Enter number(s) or just hit Return to quit:hello
That wasn't a number. Try again!
Sum: 168.6
Enter number(s) or just hit Return to quit:-0.99
added -0.99 to 168.6
Sum: 167.60999999999999
Enter number(s) or just hit Return to quit:
That was fun!
I remembered all your 3 numbers:
123.00
45.60
-0.99
--------
167.61
Related
I work in sublime text 3 and I know my code is very simply.when I enter input and press enter key in keyboard nothing else happen and ready still to get input from keyboard.what's wrong?thanks for any help.
def is_even(k):
if k % 2 == 0:
print ("%s is even." % (k))
return True
print (is_even(int(input("Please enter number: "))))
Try doing it like this.
def is_even(k):
if k % 2 == 0:
return True
number = int(input("Please enter number: "))
if is_even(number)==True:
print ("%s is even." % (number))
else:
print ("%s is not even." % (number))
I have written the Python code below (actually it's my solution for an exercise from page 80 of "Teach yourself Python in 24 hours").
The idea is: there are 4 seats around the table, the waiter knows for how much each seat ordered, enters those 4 amounts and gets a total.
If the raw_input provided is not a number (but a string) my code kicks the person out. The goal, however, is to give an error message ("this entry is not valid") and ask for the input again - until it's numeric. However, I can't figure out how to ask the user for the raw input again - because I am already inside a loop.
Thanks a lot for your advice!
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
break
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
Generally, when you don't know how many times you want to run your loop the solution is a while loop.
for seat in range(1,5):
my_input = raw_input("Enter: ")
while not(my_input == 'q' or isnumeric(my_input)):
my_input = raw_imput("Please re-enter value")
if my_input == 'q':
break
else:
total += float(my_input)
As Patrick Haugh and SilentLupin suggested, a while loop is probably the best way. Another way is recursion- ie, calling the same function over and over until you get a valid input:
def is_numeric(value):
try:
input = float(value)
except ValueError:
return False
else:
return True
def is_q(value):
return value == 'q'
def is_valid(value, validators):
return any(validator(input) for validator in validators)
def get_valid_input(msg, validators):
value = raw_input(msg)
if not is_valid(value, validators):
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(value)
value = get_valid_input(msg, validators)
return value
total = 0
for seat in range(1,5):
print 'Note the amount for seat', seat, 'and'
myinput = get_valid_input("enter it here ['q' to quit]: ", [is_q, is_numeric])
if myinput == 'q':
break
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
if myinput == 'q':
print "Goodbye!"
else:
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
In the above code, get_valid_input calls itself over and over again until one of the supplied validators produces something truthy.
total = 0
for seat in range(1,5):
incorrectInput = True
while(incorrectInput):
print 'Note the amount for seat', seat, 'and'
myinput = raw_input("enter it here ['q' to quit]: ")
if myinput == 'q':
print 'Goodbye'
quit()
elif is_numeric(myinput):
floatinput = float(myinput)
total = total + floatinput
incorrectInput = False
else:
print 'I\'m sorry, but {} isn\'t valid. Please try again'.format(myinput)
total = round(total, 2)
print "*****\nTotal: ${}".format(total)
print "Goodbye!"
This is a simple program to check if a number is odd or even.I want to check if the user wants to continue or not and when I run it I get an Invalid Syntax Error on the break line, what have I got wrong?
while True:
if cont != "no":
num = (int(input("Type a number. ")))
num_remainder = num % 2
if num_remainder == 0:
print ()
print (num, " is an even number.")
else:
print ()
print (num, " is an odd number.")
cont= (input("Would you like to continue?")
continue
else:
break
Thanks
I think this is simpler,
while True:
num = int(input("Type a number. "))
print () # blank line before assert whether is or not a even number
if num % 2 == 0:
print (num, " is an even number.")
else:
print (num, " is an odd number.")
if input("Would you like to continue?") == 'no': # Ohh, you want to break now.
break
I'm currently learning Python and am creating a maths quiz.
I have created a function that loops, first creating a random maths sum, asks for the answer and then compares the input to the actual answer; if a question is wrong the player loses a point - vice versa. At the end a score is calculated, this is what I'm trying to return at the end of the function and print in the main.py file where I receive a NameError 'score' is not defined.
I have racked my head on trying to figure this out. Any help / suggestions would be greatly appreciated!
#generateQuestion.py
`def generate(lives, maxNum):
import random
score= 0
questionNumber = 1
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
print ('All done!')
return score
`
My main file
#main.py
import random
from generateQuestion import generate
#Welcome message and name input.
print ('Welcome, yes! This is maths!')
name = input("What is your name: ")
print("Hello there",name,"!" )
print('\n')
#difficulty prompt
while True:
#if input is not 1, 2 or 3, re-prompts.
try:
difficulty = int (input(' Enter difficulty (1. Easy, 2. Medium, 3. Hard): '))
except ValueError:
print ('Please enter a number between 1 to 3.')
continue
if difficulty < 4:
break
else:
print ('Between 1-3 please.')
#if correct number is inputted (1, 2 or 3).
if difficulty == 1:
print ('You chose Easy')
lives = int(3)
maxNum = int(10)
if difficulty == 2:
print ('You chose Medium')
lives = int(2)
maxNum = int(25)
if difficulty == 3:
print ('You chose Hard')
lives = int(1)
maxNum = int(50)
print ('You have a life count of', lives)
print('\n')
#generateQuestion
print ('Please answer: ')
generate(lives, maxNum)
print (score)
#not printing^^
'
I have tried a different method just using the function files (without the main) and have narrowed it down to the problem being the returning of the score variable, this code is:
def generate(lives, maxNum):
import random
questionNumber = 1
score= 0
lives= 0
maxNum= 10
#evalualates question to find answer (maths = answer)
while questionNumber <=10:
try:
ops = ['+', '-', '*', '/']
num1 = random.randint(0,(maxNum))
num2 = random.randint(0,10)
operation = random.choice(ops)
question = (str(num1) + operation + str(num2))
print ('Question', questionNumber)
print (question)
maths = eval(str(num1) + operation + str(num2))
answer=float(input("What is the answer? "))
except ValueError:
print ('Please enter a number.')
continue
if answer == maths:
print ('Correct')
score = score + 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
elif lives == 1:
print ('You died!')
print('\n')
break
else:
print ('Wrong answer. The answer was actually', maths)
lives = lives - 1
questionNumber = questionNumber + 1
print ('Score:', score)
print ('Lives:', lives)
print('\n')
continue
if questionNumber == 0:
return score
def scoreCount():
generate(score)
print (score)
scoreCount()
I think the problem is with these last lines in main:
print ('Please answer: ')
generate(lives, maxNum)
print ('score')
You are not receiving the returned value. It should be changed to:
print ('Please answer: ')
score = generate(lives, maxNum) #not generate(lives, maxNum)
print (score) # not print('score')
This will work.
The way it works is not:
def a():
score = 3
return score
def b():
a()
print(score)
(And print('score') will simply print the word 'score'.)
It works like this:
def a():
score = 3
return score
def b():
print(a())
def adding():
total = 0
x = 0
while x != 'done':
x = int(raw_input('Number to be added: '))
total = x + total
if x == 'done':
break
print total
I cant figure out how to add numbers that a user is inputing, and then stop and print the total when they input 'done'
I'm assuming it's yelling at you with a ValueError when the user inputs "done"? That's because you're trying to cast it as an int before checking if it's a number or the sentinel. Try this instead:
def unknownAmount():
total = 0
while True:
try:
total += int(raw_input("Number to be added: "))
except ValueError:
return total
Alternatively, you can change your own code to work by doing:
def unknownAmount():
total = 0
x = 0
while x != "done":
x = raw_input("Number to be added: ")
if x == "done":
continue
else:
total += int(x)
return total
But beware that if the user enter "foobar", it will still throw a ValueError and not return your total.
EDIT: To address your additional requirement from the comments:
def unknownAmount():
total = 0
while True:
in_ = raw_input("Number to be added: ")
if in_ == "done":
return total
else:
try:
total += int(in_)
except ValueError:
print "{} is not a valid number".format(in_)
This way you check for the only valid entry that's NOT a number first ("done") then holler at the user if the cast to int fails.
There are many similar questions here, but what the hell. Simplest would be:
def adding():
total = 0
while True:
answer = raw_input("Enter an integer: ")
try:
total += int(answer)
except ValueError:
if answer.strip() == 'done':
break
print "This is not an integer, try again."
continue
return total
summed = adding()
print summed
More fancy take on problem would be:
def numbers_from_input():
while True:
answer = raw_input("Enter an integer (nothing to stop): ")
try:
yield int(answer)
except ValueError:
if not answer.strip(): # if empty string entered
break
print "This is not an integer, try again."
continue
print sum(numbers_from_input())
but here are some python features you may not know if you are begginer