This calculator works in Python 2:
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
if operation == 1:
print ("The result is:", firstnum+secondnum)
if operation == 2:
print ("The result is:", firstnum-secondnum)
if operation == 3:
print ("The result is:", firstnum*secondnum)
if operation == 4:
print ("The result is:", firstnum/secondnum)
But in Python 3 the script does nothing after accepting input.
--UPDATE--
After fixing thanks the help of #moses-koledoye, I'll post the final source code, it could be help for some other newbie.
print ("First calculator!")
print ("")
firstnum=input ("Insert the first number: ")
print ("")
print ("Available operations:\n 1:Addition\n 2:Subtraction\n 3:Multiplication\n 4:Division\n")
operation=input ("Insert the number of operation: ")
if int(operation) >4:
print ("You mistyped")
exit(0)
print ("")
secondnum=input ("Insert the second number: ")
firstnum=int(firstnum)
secondnum=int(secondnum)
print ("")
if operation == "1":
print ("The result is:", firstnum+secondnum)
elif operation == "2":
print ("The result is:", firstnum-secondnum)
elif operation == "3":
print ("The result is:", firstnum*secondnum)
elif operation == "4":
print ("The result is:", firstnum/secondnum)
You're comparing strings with integers:
if operation == 1 # '1' == 1
will always be False, so none of the if blocks is executed.
Do a string-string comparison instead:
if operation == '1'
And when the if block conditions are fixed, others bugs will show up:
firstnum + secondnum
This will concat your strings and not perform a numerical operation as you intend, while operation -, * and / will raise TypeError. You should cast your operands, firstnum and secondnum to the appropriate type: float or int.
Besides, you could also chain all the if clauses into one if-elif clause
Related
print("Give me two numbers, I'll sum them")
print("Enter 'q' to quit")
while True:
num1 = input("Please, enter a number here: ")
if num1 == 'q':
break
num2 = input("Please, enter a number here: ")
if num2 == 'q':
break
try:
sum = int(num1) + int(num2)
except ValueError:
print("'q' entered, program exit 0")
else:
print(sum)
Hi the above program in Python3 works fine when numbers are inputted.
But when I input q, it just exits with no exception.
May you please assist me with this issue?
Thank you very much indeed.
the break statement will exit your loop without printing anything, because your try-except test is after breaks.
Here is what you can do:
print("Give me two numbers, I'll sum them")
print("Enter 'q' to quit")
while True:
num1 = input("Please, enter a number here: ")
if num1 == 'q':
print("'q' entered, program exit 0")
break
num2 = input("Please, enter a number here: ")
if num2 == 'q':
print("'q' entered, program exit 0")
break
if not num1.isdecimal() or not num2.isdecimal():
print('Wrong input, please enter decimal numbers !')
continue
sum = int(num1) + int(num2)
print(sum)
When the user enters nothing, it is supposed to loop back and ask the question again. It performs correctly with every other type of input.
Here is the code:
string = ""
def str_analysis(string):
while True:
if string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
break
else:
print(str(string)+ " is a smaller number than expected")
break
elif string.isalpha():
print(string + " is an alphabetical character")
break
elif string == "":
print("")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
print(str_analysis(input("Enter word or integer: ")))
There are a few things in your code that make no sense.
1:
print(str_analysis(input("Enter word or integer: ")))
You are trying to print the output of a function that has no return value
2:
It cant loop back and ask the question again, because the input is not taken inside of the function.
3:
If the string is empty you dont break the code but constantly print newlines.
Here is some code wich I think should do what you wanted:
def str_analasys():
while True:
string = input("Enter word or integer: ")
if string == '':
continue
elif string.isdigit():
if int(string) > 99:
print(str(string)+ " is a pretty big number!")
else:
print(str(string)+ " is a smaller number than expected")
elif string.isalpha():
print(string + " is an alphabetical character")
else:
print(string + " is a surprise! It's neither all alpha nor all digit characters!")
break
str_analasys()
This because when string is empty you are just printing an empty ""
elif string == "":
print("")
# break it here or take input again
# break or string = input()
My code works to quit the program for my 'elif' and 'else' statements, but when I input 'yes', I'm stuck in this input loop where anything I input still rolls the dice. How can I get out of the program by inputting 'no', once I've already inputted 'yes' and entered the loop?
import random
min = 1
max = 6
prompt = "Roll dice? Type yes or no. "
roll_dice = input(prompt)
while roll_dice:
if roll_dice == "yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
input(prompt)
elif roll_dice == "no":
print ("see you later!")
break
else:
print ("invalid answer")
break
Instead of just doing:
input(prompt)
Which does nothing with the given input which means
roll_dice will always be equal to yes and you will be stuck in an infinite loop.
You should use:
roll_dice = input(prompt)
which sets roll_dice to the new value, and hence lets you exit out of the loop.
You can modify the code in this manner:
while roll_dice =="yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
roll_dice = input(prompt)
You must include roll_dice for getting the return value from the input function and validating if the response is yes, no or invalid.
In your code, input returns a value but that value is never checked after the if statement is executed once.
while roll_dice =="yes":
print ("you rolled", random.randint(min, max), random.randint(min, max))
input(prompt)
I am creating a simple calculator with Python as my first "bigger" project.
I am trying to use def function and when i am trying to call that function it gives "undefined name" error message.
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
def calculation (argnum1, argnum2):
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
number = argnum1
number = argnum2
result = argnum1 + argnum2
print (result)
print("-"*25)
return number
return result
if user_input == "quit":
break
elif user_input == "+":
calculation (argnum1, argnum2)
I expect the output of argnum1 + argnum 2 result.
You have needlessly defined your function to take two parameters, which you cannot provide as they are defined inside the function:
def calculation (argnum1, argnum2): # argnum1 and argnum2 are immediately discarded
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
# do things with argnum1 and argnum2
...
calculation(argnum1, argnum2) # argnum1 and argnum2 are not defined yet
Note that the body of a function is executed only when the function is called. By the time you call calculation, argnum1 and argnum2 are not defined - and even then, they only get defined in another scope.
Ideally, move the input call outside of your function:
def calculation (argnum1, argnum2):
# do things with argnum1 and argnum2
...
argnum1 = float (input("Enter your fist number: ")) # argnum1 is defined here
argnum2 = float (input("Enter your second number: "))
calculation(argnum1, argnum2)
Note that you should define your function outside the loop. Otherwise, it is needlessly redefined on every iteration. There is also no point in having multiple return statements after one another.
Your code should look like this:
def add(argnum1, argnum2):
result = argnum1 + argnum2
print (result)
print("-"*25)
return result
while True:
print ("Options: ")
print ("Enter '+' to add two numbers")
print ("Enter '-' to subtract two numbers")
print ("Enter '*' to multiply two numbers")
print ("Enter '/' to divide two numbers")
print ("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
argnum1 = float (input("Enter your fist number: "))
argnum2 = float (input("Enter your second number: "))
add(argnum1, argnum2)
You can move the function definition out of the while block.
def calculation():
argnum1 = float(input("Enter your fist number: "))
argnum2 = float(input("Enter your second number: "))
result = argnum1 + argnum2
print(result)
return result
while True:
print("Options: ")
print("Enter '+' to add two numbers")
print("Enter '-' to subtract two numbers")
print("Enter '*' to multiply two numbers")
print("Enter '/' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")
if user_input == "quit":
break
elif user_input == "+":
calculation()
using a nested if statement and my indentation seems correct thru out yet still reviving a syntax error.thank you
# FIGHT Dragons
if ch3 in ['y', 'Y', 'Yes', 'YES', 'yes']:
# WITH SWORD
if sword == 1:
print ("You only have a sword to fight with!")
print ("You quickly jab the Dragon in it's chest and gain an advantage")
time.sleep(2)
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
print (" Fighting... ")
print (" YOU MUST HIT ABOVE A 5 TO KILL THE DRAGON ")
print ("IF THE DRAGON HITS HIGHER THAN YOU, YOU WILL DIE")
print ("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~")
time.sleep(2)
fdmg1 = int(random.randint(3, 10))
edmg1 = int(random.randint(1, 5))
print ("you hit a", fdmg1)
print ("the dragon hits a", edmg1)
time.sleep(2)
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
return complete
this is where i run into a syntax error
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
return complete
else:
print ("You killed the drgon!")
complete = 1
return complete
Your return must be at the end of the if...elif...else statement. This works :
if edmg1 > fdmg1:
print ("The drgon has dealt more damage than you!")
complete = 0
elif fdmg1 < 5:
print ("You didn't do enough damage to kill the drgon, but you manage to escape")
complete = 1
else:
print ("You killed the drgon!")
complete = 1
return complete
Note that if the first if-condition is True, Python won't check for the subsequent ones.