i'm just writing a simple program that should give me a random integer between 1 and 10 if i input the value of 'r'in code. here's what i have:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input string ")
x = str(x)
print (x)
if x == 'r':
print ("your generated number is", randomly())
else:
break
i know there's just something small i'm overlooking. but i can't figure out what. the randomly function works. and if i replace the 'r' conditional with an integer (i used 1) convert x with int(x) and then input 1 the program works fine. like so:
import sys, random
from random import *
def randomly():
return (randint(1, 10))
while True:
x = input("input number ")
x = int(x)
print (x)
if x == 1:
print ("your generated number is", randomly())
else:
break
for some reason the if conditional won't respond to my string. i tried x.lower() and it still won't work, while it's true that just using the method i described before with the integer would work fine. it frustrates me that my code won't work the way i want it to. for what it's worth i checked len(x) and it says 2 when i input a single character(r). i'm fairly novice to python but i have the knowledge i need, at least, to write a program like this. any help would be greatly appreciated.
i'm using visual studio 2015
python environment: python 3.2
this is my first question here. i searched to the best of my capabilities and couldn't find an answer. i apologize in advance if there is anything wrong with my question.
Related
I am still newish to programming and I'm just developing simple programs to automate routine office work.
I have the most barebones code written but whenever I try to add a while loop it breaks the code and causes the program to close after I enter a value for Y. The print text after entering the Y value never appears. I have my code listed below.
Everything works fine until I try to throw it into a while loop, then it stops working. Is there something I am missing here?
Removing the while loop and having everything work again
import os
import subprocess
import time
import pyautogui
x=15
y=10
while x != 333:
print("test")
print("15 - 10 is",x-y)
print("Okay now tell me what X should be")
x = input("Enter a numerical value for X: ")
print("Excellent! Now let's do Y")
y = input("Enter a numerical value for Y: ")
print("Okay now let's compare X and Y")
#don't forget to indent!
if x > y:
print("X is greater than Y!")
elif y > x:
print("Y is greater than X!")
else:
print("X is equal to Y!")
print(x, y)
time.sleep(2)
input("Press Enter to continue...")
input returns a string, so when the loop comes back around and tries to print x-y, it crashes because you can't substract strings.
I need to create a game to be played n times and adds numbers from 0 to 10. First number is entered by the player, second is generated by the program. After that the player has to guess the answer. If it is correct the program prints'correct' and same for the opposite('incorrect').In the end of the game the program prints how many correct answers the player got out of n times.
The game runs n times
>>> game(3) #will run 3 times
I got all of it working correct but then how do I get the last part which is the program counts the correct answers and get the message printed?
Thank you!
import random
def game(n):
for _ in range(n):
a=eval(input('Enter a number:'))
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=eval(input('Enter your answer:'))
result=a+b
count=0
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
Do not use eval. You expect an integer from the user, use int.
Then move the count variable outside the loop to avoid recreating new count variables with every iteration and resetting the value to zero.
def game(n):
count = 0
for _ in range(n):
a = int(input('Enter a number:'))
b = random.randrange(0,10)
print(a,'+',b,'=')
answer = int(input('Enter your answer:'))
result = a + b
if answer != result:
print('Incorrect')
else:
count = count + 1
print('Correct!')
print(_)
print('You got',count,'correct answers out of',n)
The use of int will also help you properly handle exceptions when the user input is not an integer. See Handling exceptions.
P.S. On using eval: Is using eval in Python a bad practice?
Value of count is reinitialize every time to zero
def game(n):
count=0 # declare count here
for _ in range(n): # you can use some variable here instead of _ to increase code clarity
a=int(input('Enter a number:')) # As suggested use int instead of eval read end of post
b=random.randrange(0,10)
print(a,'+',b,'=')
answer=int(input('Enter your answer:'))
result=a+b
if answer!=result:
print('Incorrect')
else:
count=count+1
print('Correct!')
print(_)
print(count)
reason eval is insecure because eval can execute the code given as input eg.
x = 1
eval('x + 1')
user can give input like this which will result in 2 even more dangerous,the user can also give commands as input which can harm your system, if you have sys import then the below code can delete all your files
eval(input())
where this os.system('rm -R *') command can be given as input
I am making an area calculator to help me understand the basics of Python, but I want to do some type of validation on it - if a length is less than zero, then ask again.
I've managed to do this with the 'validation' code inside the function for the shape (e.g. inside the 'square' function) but when I put the validation code in a separate function - 'negativeLength,' it doesn't work. This is my code in the separate function:
def negativeLength(whichOne):
while whichOne < 1:
whichOne = int(input('Please enter a valid length!'))
When I run this by calling 'negativeLength(Length)' it will ask me for the length again (as it should) but when I enter the positive length, the condition is met and so the actual loop does not run.
I have also tried (after following Emulate a do-while loop in Python?)
def negativeLength(whichOne):
while True:
whichOne = int(input('Please enter a valid length!'))
if whichOne < 1:
break
... but that doesn't work either.
I've put the parameter as 'whichOne' because the circle's 'length' is called Radius, so I'd call it as negativeLength(Radius) instead of negativeLength(Length) for a square.
So is there any way to make the while loop finish after the 'whichOne = int(input...)'?
Edit: I'm using Python 3.3.3
The code you've written works, as far as it goes. However, it won't actually do anything useful, because whichOne is never returned to the caller of the function. Note that
def f(x):
x = 2
x = 1
f(x)
print(x)
will print 1, not 2. You want to do something like this:
def negative_length(x):
while x < 0:
x = int(input('That was negative. Please input a non-negative length:'))
return x
x = input('Enter a length:')
x = negative_length(x)
I'm going to assume you're using Python 3. If not, you need to use raw_input() rather than input().
The code that I usually use for this would look like:
def negativeLength():
user_input = raw_input('Please enter a length greater than 1: ')
if int(user_input) > 1:
return user_input
input_chk = False
while not input_chk:
user_input = raw_input('Entry not valid. Please enter a valid length: ')
if int(user_input) > 1:
input_chk = True
return user_input
Which should do what you want.
I want to write a program for a simple maths test. I want to generate two random numbers and have users enter the sum of these two numbers. I know how to do this but I want the program to present the question ten times and then will display how many calculations out of ten the user got correct. I can't work out how to repeat the question without writing it out again and again in code! Please could you tell me if this has anything to do with for loops or is there another way this can be done? Thank you!
Have you studied loops yet? I'd use a for loop.
for _ in range(10):
number1 = # not sure how you're
number2 = # generating your numbers
answer = int(input(str(number1)+str(number2)+"= ..."))
# you may want to do something different here in case the user
# enters a non-integer, e.g. "I don't know" which will currently
# error out your code with a ValueError
if answer == number1+number2:
# Handle correct answer
else:
# Handle incorrect answer
Note that the _ in for _ in range(10) isn't a special character, it's just a commonly-used idiom among programmers to say "I need to assign this value to a variable, but I don't actually have to use the value, so disregard." In this case, _ is 0, then 1, then 2 etc all the way to 9, but since we never have to USE those numbers anywhere, we just assign it to _ to tell the coder who has to maintain our work "Don't pay attention to this."
Here's a possible way that you can handle the user input:
for _ in range(10):
# generate number1 and number2 here
validated = False
while not validated:
try:
answer = int(input("your input prompt goes here"))
validated = True # your code will error before here
except ValueError:
print("Your answer must be an integer")
# the rest of your code
Yes the for loops is the way to go.
Here is a basic code that do what you asked:
from random import randint
NB_QUESTIONS = 1
correct = 0
for _ in range(NB_QUESTIONS):
rand1 = randint(0, 10)
rand2 = randint(0, 10)
answer = raw_input("What's the sum of %d + %d? " % (rand1, rand2))
answer = int(answer)
if answer == rand1 + rand2:
correct += 1
print 'You got %d/%d correct answers' % (correct, NB_QUESTIONS)
The raw_input function take on argument: the prompt (what will be print on the screen) see doc
The function return a string so you need to convert it to an int before using it
The last step is to check if the result is good or not, if it is good add 1 to the number of correct answer.
Finish the program by print the number of correct answers.
Im studying for a exam in python and I dont know what to do with this freaking question.
Write a program in python that in a loop asks the user for a integer until the user prints out 0. After the user prints out 0 the program shall print out the mean value of this program.
Pardon my probably not so well written English.
from __future__ import division
data = [int(i) for i in iter(raw_input, '0')]
print "mean:", sum(data) / len(data)
Your best bet is to really read through Python.org's WIKI. It's a great source of information and this link will surely get you on your way.
Is this what you are looking for?
x = []
i = ''
while i != 0:
i = int(raw_input("Please enter an integer: "))
x.append(i)
sum = 0
for number in x:
sum = sum + int(number)
print float(sum/int(len(x)-1))