Well I just started learning Python so I don't understand how to make my code correct (Worth to SAY that I learn it from youtube))). What I want from the code is -- if the assignment num1 has 8 in the end and it should be printed by command print, and if it doesn't just print nothing.
import re
def x():
num1 = 5894652138
vav = re.match(r'[8]''$', num1)
print vav
x()
You don't need to use re here.
To check the last digit in decimal number, you should use the modulos with 10:
num1 = 5894652138
if num1 % 10 == 8:
print num1
def x():
num1 = 5894652138
num2 = str(num1)
if (num2.endswith("8")):
print num1
you could do this to see if 8 is at the end.
Related
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says :
TypeError: %d format: a number is required, not str
from sys import argv
file_name, num1, num2 = argv
int(argv[1])
int(argv[2])
def addfunc(num1, num2):
print "This function adds %d and %d" % (num1, num2)
return num1 + num2
addsum = addfunc(num1, num2)
print "The final sum of addfunc is: " + str(addsum)
When I run filename.py 2 2, does argv put 2 2 into strings? If so, how do I convert these into integers?
Thanks for your help.
sys.argv is indeed a list of strings. Use the int() function to turn a string to a number, provided the string can be converted.
You need to assign the result, however:
num1 = int(argv[1])
num2 = int(argv[2])
or simply use:
num1, num2 = int(num1), int(num2)
You did call int() but ignored the return value.
Assign the converted integers to those variables:
num1 = int(argv[1]) #assign the return int to num1
num2 = int(argv[2])
Doing just:
int(argv[1])
int(argv[2])
won't affect the original items as int returns a new int object, the items inside sys.argv are not affected by that.
Yo modify the original list you can do this:
argv[1:] = [int(x) for x in argv[1:]]
file_name, num1, num2 = argv #now num1 and num2 are going to be integers
Running int(argv[1]) doesn't actually change the value of argv[1] (or of num1, to which it is assigned).
Replace this:
int(argv[1])
int(argv[2])
With this:
num1 = int(num1)
num2 = int(num2)
and it should work.
The int(..), str(...) etc functions do not modify the values passed to them. Instead, they return a reinterpretation of the data as a different type.
#This part of the code will only get numbers from user
while True:
#Using while True will allow me to loop and renter if user input is wrong. While True will go above Try Catch
try:
# Using try: and except: will allow to end the program without crash however then need to be indented
# Try goes before the def name
def getNumbers():
num1=int(input("Enter 1st number: "))
num2=int(input("Enter 2nd number: "))
getNumbers()
break# the while will stop when both values are numbers
except:
print("Incorrect input detected, try again")
#This part of the code will add the 2 numbers
def addNums():
What do I put here so that I can use num1+num2
addNums()
def subNums():
What do I put here so that I can use num1-num2
addNums()
I wrote a Calculator program but over there I declared those num1 and num2 as global variables in side getNumbers def. Someone mentioned that is not a good/ideal way which is why I wanted to try this approach.
Thanks in advance.
In order to use global variables inside of a function, use the global keyword:
x = 1
y = 2
def add() :
global x, y
return x + y
EDIT
Actually, your "question" is really unclear. You say you are not willing to use global-variables in your code, but you wrote:
def addNums():
What do I put here so that I can use num1+num2
addNums()
The problem is that num1 and num2 don't exist at this place. If you want to use them, then they are global variables.
As far as I understand, what you want is just a function:
def addNums(x, y):
return x+y
addNums(num1, num2)
I don't know what's your doubt, it's not clear in your post.
Why can't you do in this way (just for e.g, you can make it better):--
Blockquote
def subNums(a, b):
return (a - b)
def addNums(a, b):
return (a + b)
def getNumbers():
while True:
try:
num1 = int(input("Enter 1st number: "))
num2 = int(input("Enter 2nd number: "))
return (num1, num2)
except:
print("Incorrect input detected, try again")
a, b = getNumbers()
print ("sum of %d and %d : %d" % (a, b, addNums(a, b)))
print ("difference of %d and %d : %d" % (a, b, subNums(a, b)))
Hope this will help.
I am very much interested in Python and I decided to learn it.
I covered many things but I am stuck when try to make a Calculator in which we just need to type the numbers and the operation type
For Example- 10 ^ 2
The thing that happens is I get no answer. And i use Command Prompt
for the output.
My Code looks like this:
# Calculator
print " "
print " Calculator "
print " "
num = int(raw_input(">> ")).split()
num1 = int(num[0])
op = num[1]
num2 = int(num[2])
if (op=='+'):
print ">>>", num1 + num2
elif (op=='-'):
print ">>>", num1 - num2
elif (op=='*'):
print ">>>", num1 * num2
elif (op=='/'):
print ">>>", num1 / num2
elif (op=='^'):
print ">>>", pow(num1,num2)
elif (op=='%'):
print ">>>", num1 % num2
I use Python 2.7.
Please Help Me For The Same.
You have to remove the int cast, that is
num = raw_input(">> ").split() # remove the int cast
Output will then be:
>> 10 ^ 2
>>> 100
Change
num = int(raw_input(">> ")).split()
To
num = raw_input(">> ").split()
If you enter 2 ^ 10, for example, num will now be the array ['2', '^', '10'] and the rest of your code will work.
If you do int() on your raw_input it will not work since you are trying to convert a string like "2 ^ 10" to an int.
num = int(raw_input(">> ")).split()
should be changed to
num = (raw_input(">> ")).split()
you cannot split a number at least for what I know
My task is to create a maths quiz for primary school children. this is what I have done so far:
import random
import math
def test():
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+', '-', '*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
print ("What is {} {} {}?".format(num1, operation, num2))
userAnswer= int(input("Your answer:"))
if userAnswer != num3:
print ("Incorrect. The right answer is {}".format(num3))
return False
else:
print ("correct")
return True
username=input("What is your name?")
print ("Welcome "+username+" to the Arithmetic quiz")
correctAnswers=0
for question_number in range(10):
if test():
correctAnswers +=1
print("{}: You got {} answers correct".format(username, correctAnswers))
What I now need to do is make my program only create questions with positive answers. e.g nothing like 3-10=-7
I've tried searching everywhere online but I cant find anything so I've turned to you guys for help. Any help will be appreciated :)
What I would recommend is:
#Random code...
if num1<num2:
num1, num2 = num2, num1
#Rest of program
So that 3 - 7 = -4 becomes 7 - 3 = 4
The reason I recommend doing this is that the answer would still be the same as the previous equation, just positive instead of negative, so you are still testing the same numbers.
Keep the larger number on the left of the expression, also use operator instead of eval:
from operator import add, sub, mul
def test():
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
d = {"+": add, "-": sub, "*": mul}
operation = random.choice(list(d)))
num1 = max(num1, num2)
num2 = min(num1, num2)
num3 = d[operation](num1, num2)
print("What is {} {} {}?".format(num1, operation, num2))
userAnswer = int(input("Your answer:"))
if userAnswer != num3:
print("Incorrect. The right answer is {}".format(num3))
return False
else:
print("correct")
return True
username = input("What is your name?")
print("Welcome {} to the Arithmetic quiz".format(username))
correctAnswers = sum(test() for question_number in range(10))
print("{}: You got {} answers correct".format(username, correctAnswers))
Or as #jonclements suggests sorting will also work:
num2, num1 = sorted([num1, num2])
On another note you should really be using a try/except to verify the user input and cast to an int otherwise the first value that cannot be cast to an int your program will crash.
You can choose the numbers such that num2 will be between 1 and num1 like:
num1=random.randint(1, 10)
num2=random.randint(1, num1)
or that num1 > num2:
n1=random.randint(1, 10)
n2=random.randint(1, 10)
num1 = max(n1,n2)
num2 = min(n1,n2)
i would go with the first option. no extra variables, no extra lines.
after the code that chooses the random numbers you can add this while loop:
while num3<0:
num1=random.randint(1, 10)
num2=random.randint(1, 10)
ops = ['+','-','*']
operation = random.choice(ops)
num3=int(eval(str(num1) + operation + str(num2)))
It will enter this loop every time the answer is negative. This will ensure that the answer is positive when the program quits the loop.
A change in one line should do it:
if num1 > num2:
num3=int(eval(str(num1) + operation + str(num2)))
else:
num3=int(eval(str(num2) + operation + str(num1)))
I'm pretty new at python and I've been playing with argv. I wrote this simple program here and getting an error that says :
TypeError: %d format: a number is required, not str
from sys import argv
file_name, num1, num2 = argv
int(argv[1])
int(argv[2])
def addfunc(num1, num2):
print "This function adds %d and %d" % (num1, num2)
return num1 + num2
addsum = addfunc(num1, num2)
print "The final sum of addfunc is: " + str(addsum)
When I run filename.py 2 2, does argv put 2 2 into strings? If so, how do I convert these into integers?
Thanks for your help.
sys.argv is indeed a list of strings. Use the int() function to turn a string to a number, provided the string can be converted.
You need to assign the result, however:
num1 = int(argv[1])
num2 = int(argv[2])
or simply use:
num1, num2 = int(num1), int(num2)
You did call int() but ignored the return value.
Assign the converted integers to those variables:
num1 = int(argv[1]) #assign the return int to num1
num2 = int(argv[2])
Doing just:
int(argv[1])
int(argv[2])
won't affect the original items as int returns a new int object, the items inside sys.argv are not affected by that.
Yo modify the original list you can do this:
argv[1:] = [int(x) for x in argv[1:]]
file_name, num1, num2 = argv #now num1 and num2 are going to be integers
Running int(argv[1]) doesn't actually change the value of argv[1] (or of num1, to which it is assigned).
Replace this:
int(argv[1])
int(argv[2])
With this:
num1 = int(num1)
num2 = int(num2)
and it should work.
The int(..), str(...) etc functions do not modify the values passed to them. Instead, they return a reinterpretation of the data as a different type.