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))
Related
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
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
My code is creating an infinite loop when I enter a letter at the command prompt. I think that len(sys.argv) > 1 is causing the problem, since if I enter a letter at the command prompt this will always be true and the loop will not end. Not sure how I could work around this though... any advice for this newbie would be helpful. Thanks!
"""
Have a hard-coded upper line, n.
Print "Fizz buzz counting up to n", substituting in the number we'll be counting up to.
Print out each number from 1 to n, replacing with Fizzes and Buzzes as appropriate.
Print the digits rather than the text representation of the number (i.e. print 13 rather than thirteen).
Each number should be printed on a new line.
"""
# entering number at command line: working
# entering letter at command line: infinite loop
# entering number at raw_input: works, runs process
# entering letter at raw_input: working
import sys
n = ''
while type(n)!=int:
try:
if len(sys.argv) > 1:
n = int(sys.argv[1])
else:
n = int(raw_input("Please enter a number: "))
except ValueError:
print("Please enter a number...")
continue
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)`enter code here`
Try casting first catching a value and index error:
import sys
try:
n = int(sys.argv[1])
except (IndexError,ValueError):
while True:
try:
n = int(raw_input("Please enter a number: "))
break
except ValueError:
print("Please enter a number...")
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)
If you are not actually trying to take command line inputs just use the while True:
while True:
try:
n = int(raw_input("Please enter a number: "))
break # input was valid so break the loop
except ValueError:
print("Please enter a number...")
print("Fizz buzz counting up to {}".format(n))
for y in range(1,n+1):
if y % 5 == 0 and y % 3 == 0:
print('fizzbuzz')
elif y % 3 == 0:
print('fizz')
elif y % 5 == 0:
print('buzz')
else:
print(y)
userInput = []
for i in xrange(1, 10):
userInput.append(raw_input('Enter the %s number: '))
userInput = ''
while len(userInput) != 1:
userInput = raw_input(':')
guessInLower = userInput.lower()
print"the numbers you have entered are: ", userInput
so I am trying to make a program that takes 10 single digit inputs and then puts them into a single string then after it hits 10 inputs of single digits it then prints out all the single digit inputs I have gotten this far but I can't find a way for it to check to first. Any suggestions?
You should put it all inside a single loop and check if the input is a single digit:
user_inp = ""
while len(user_inp) < 10:
inp = raw_input("Enter a digit")
if len(inp) == 1 and inp.isdigit(): # check length and make sure a digit is entered
user_inp += inp
else:
print("Invalid input")
print("The numbers you have entered are: {}".format(user_inp))
From what you are saying, the following code is what you want:
Demo on repl.it
Code:
userInput = ""
for i in xrange(1, 11):
userInput += (raw_input('Enter the %s number: '))
print"the numbers you have entered are: ", userInput
Output:
Enter the %s number: 1
Enter the %s number: 2
Enter the %s number: 3
Enter the %s number: 4
Enter the %s number: 5
Enter the %s number: 6
Enter the %s number: 7
Enter the %s number: 8
Enter the %s number: 9
Enter the %s number: 0
the numbers you have entered are: 1234567890
I want the program to remove ()'s and -'s which could possibly be entered when some one enters their phone #. I also want to make sure that is is 10 numerical characters long if not produce a loop.
p = raw_input("Please enter your 10 digit Phone Number")
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
p = only_numerics(p)
valid_phone = False
while not valid_phone:
if p > "0000000000" and p < "9999999999" and len(p) == 10 :
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
If I type in less than 10 numbers I get repeating of the else print command. I would like it to go back to raw input ("please enter your 10 digit Phone Number"). Is there any way to do this?
Apart from setting the "raw_input" inside the loop as James pointed out, you might be interested in using regular expressions and make your code more beautiful:
import re
phone_re = re.compile(r'\d{10}$')
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
valid_phone = False
while not valid_phone:
p = raw_input("Please enter your 10 digit Phone Number: ")
p = only_numerics(p)
if phone_re.match(p):
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
It loops back to the print statement because you define p outside of the while loop. Changing this will fix the looping issue:
valid_phone = False
while not valid_phone:
p = raw_input("Please enter your 10 digit Phone Number")
def only_numerics(p):
seq_type= type(p)
return seq_type().join(filter(seq_type.isdigit, p))
p = only_numerics(p)
if p > "0000000000" and p < "9999999999" and len(p) == 10 :
print "You have entered " + p
valid_phone=True
else:
print "You have entered an invalid choice"
def val_number(input_num):
valid_num=re.findall(r'\d+',input_num)
if len(valid_num[0])>10:
print('You have entered more than 10 digits')
else:
return(valid_num)
This python code validates an 11 digit mobile number:
valid = True
mobile_number = str(input("What is your mobile number? "))
while len(mobile_number) != 11 or mobile_number[0] != "0" or mobile_number[1:].isdigit() == False:
mobile_number = str(input("Please enter a valid mobile number: "))
valid = False
print("Your mobile number is valid")
while(True):
try:
phone_number=int(input("please enter the phone number:no spaces in between: \n"))
except ValueError:
print("mismatch")
continue
else:
phone=str(phone_number)
if(len(phone)==10):
break
else:
print("10 digits please ")
continue