I am trying to practice my modular programming with this assignment. I found out how to call the variables into my main function, but for my if statement in evenOdd(), I am not sure how to call the value. I get the error 'randNum' is not defined.
from random import randint
def genNumber():
randNum = randint(0,20000)
print("My number is " + str(randNum))
return (randNum)
def inputNum():
userNum = input("Please enter a number: ")
print("Your number is " + str(userNum))
return (userNum)
def evenOdd():
if randNum%2==0:
print("My number is even")
else:
print("My number is odd")
if userNum%2==0:
print("Your number is even")
else:
print("Your number is odd")
def main():
randNum = genNumber()
userNum = inputNum()
evenOdd()
input("Press ENTER to exit")
main()
You can either define randNum in the global scope or just pass it as a variable to your evenOdd() function, like this evenOdd( randNum ).
Related
What might I be doing wrong in this program? I recently started with Python.
##number guesser generator
import random
def main():
print("welcome to the number guessing game!")
print("You will receive three guesses!")
print("Choose a number between 1 and 100")
randomnumbergenerator()
userinput()
winorlose()
def randomnumbergenerator():
random.seed(0)
randomnumber = random.randint(1,100)
return randomnumber
def userinput():
answer1 = int(input('what is your 1st guess?'))
answer2 = int(input('what is your 2nd guess?'))
answer3 = int(input('what is your 3rd guess?'))
answers = answer1, answer2, answer3
return answers
def winorlose(randomnumber, answers):
while randomnumber != answers:
print('You lose! The correct answer equals' + randomnumber)
if randomnumber == answers:
print("You picked the correct answer! The answer was " + randomnumber)
return winorlose()
The function main is just another normal function. Python has no concept of a "main" function. You need to call the main() function manually like so
# Check if file was executed as the "main" file
# This is optional, but it ensures that if you import this file as a module,
# the main function isn't invoked
if __name__ == "__main__":
main() # Call the main function
I am pretty noob as well, but it looks as though you're building the script in a class type method but haven't added the class.
At the moment the program just runs through and creates all the functions ready for instances to be called, but you've called them within the main function which itself doesn't get called. If you were to do something like this:
class randomGenerator():
def __init__(self):
self.main()
def main(self):
print("welcome to the number guessing game!")
print("You will receive three guesses!")
print("Choose a number between 1 and 100")
self.randomnumbergenerator()
self.userinput()
self.winorlose()
def randomnumbergenerator(self):
random.seed(0)
randomnumber = random.randint(1,100)
return randomnumber
def userinput(self):
answer1 = int(input('what is your 1st guess?'))
answer2 = int(input('what is your 2nd guess?'))
answer3 = int(input('what is your 3rd guess?'))
answers = answer1, answer2, answer3
return answers
def winorlose(self, randomnumber, answers):
while randomnumber != answers:
print('You lose! The correct answer equals' + randomnumber)
if randomnumber == answers:
print("You picked the correct answer! The answer was " + randomnumber)
return winorlose()
run = randomGenerator()
then at least it will start and you can troubleshoot more. I recommend you research classes as well.
How can I use the variable 'guess' in my guessfunction() in the main function (for i in range (1,6)? I get the error that guess is not defined. Initially everything worked fine without the guessfunction, but I wanted to add the possiblity of wrong input from the user and that got me stuck.
I saw on stackexchange that it is bad practice to use global inside a function, but even with global I don't know how to solve my issue.
Is there also a way to change the int(guess) if it is possible to get the variable from the function?
Thank you!
import random, sys
print("Hello. What is your name?")
name = str(input())
print("Well, " + name + ", I am thinking of a number between 1 and 20.")
number = random.randint(1, 20)
def guessfunction():
print("Take a guess.")
guess = input()
for number_attempts in range(0,3):
try:
return guess
except ValueError:
print("Please enter a number in figures not as a word")
print("You didn't enter a number in figures after 3 tries, program ended")
sys.exit()
for i in range(1,6):
guessfunction()
if int(guess) != number:
if int(guess) < number:
print("Your guess is too low")
else:
print("Your guess is too high")
elif int(guess) == number:
print("Good job, " + name + "! You guessed my number in " + str(i) + " guesses")
sys.exit()
print("Nope. The number I was thinking of was " +str(number))
you need to initialise it in your for loop:
guess = guessfunction()
I don't know what's wrong with it.. I run it and I'm able to input a number but then it stops working. It says, "TypeError: play_game() missing 1 required positional argument: 'limit.' But I'm not sure what's missing there??
#!/usr/bin/env python3
import random
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess >= number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game()
again = input("Play again? (y/n): ")
print()
print("Bye!")
# if started as the main module, call the main function
if __name__ == "__main__":
main()
You have defined your play_game function to take limit as a parameter, but when you call this function in your main loop, you don't supply a value in the brackets of play_game().
You could either try adding that limit value that you've specified by calling it like
play_game(25)
Or, based on your code, since you're asking the user to provide a limit, call it like:
play_game(limit)
Or, if you want to be able to call play_game() without setting a limit, then change your play_game definition line to something like:
def play_game(limit=25):
Which will set a default value of 25 whenever that function is called without supplying the limit value.
Yes, play_game() needs the parameter limit. I've done a quick check on your code, and there is some additional problem
the count variable isn't initialized
you calculate the random number in every step
guess > number should be used instead of guess >= number
Here is the fixed code, it works for me. I hope it will be usefull:
import random
count = 0
number = -1
def display_title():
print("Guess the number!")
print()
def get_limit():
limit = int(input("Enter the upper limit for the range of numbers: "))
return limit
def play_game(limit):
global number, count
if number == -1:
number = random.randint(1, limit)
print("I'm thinking of a number from 1 to " + str(limit) + "\n")
while True:
guess = int(input("Your guess: "))
if guess < number:
print("Too low.")
count += 1
elif guess > number:
print("Too high.")
count += 1
elif guess == number:
print("You guessed it in " + str(count) + " tries.\n")
return
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(limit)
again = input("Play again? (y/n): ")
print()
print("Bye!")
In your main you are calling playgame() without providing a limit as an argument.
Your main should look something like
def main():
display_title()
again = "y"
while again.lower() == "y":
limit = get_limit()
play_game(10)
again = input("Play again? (y/n): ")
print()
print("Bye!")
import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
code()
code()
random_num=random.randint(0,1)
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again=="yes":
code()
else:
print("ok. Bye")
i am very new to functions so sorry if this is a rookie mistake. Any help with functions will be appreciated. Thank You.
At the very end of the "code" function you're calling it again
Try this:
import time
import random
import sys
def code():
user_num=()
user_num=int(input("What number do you want from 0-30"))
if user_num>30:
print("number needs to be smaller")
print("restart code and try again")
else:
pass
if user_num<0:
print("your number needs to be greater")
print("restart code and try again")
else:
pass
return user_num
random_num=random.randint(0,1)
user_num = code()
if random_num==user_num:
print("your number is correct")
else:
print("your number is incorrect")
time.sleep(1)
try_again=input("do you want to try again (yes/no")
if try_again in "yes":
user_num = code()
else:
print("ok. Bye")
I am trying to make a calculator using classes but I get error as "variable not defined"
What I am trying is (there are more functions in my codes, but the related code is)
def Start():
x = input("Please input what you want do to a number then the number; a whole number.\n(Example pi 2)\nYou can pow (pow 2 3; 2 to the power of 3),pi,square and cube: ").lower()
x = x.split()
Action = x[0]
number = int(x[1])
print ("Your number: " + str(number))
class Cal:
def pi():
print ("Your number multiplied by Pi: " + str(math.pi * number))
def Again():
y = input("Type 'Yes' to do another one if not type 'No': ").lower()
if "yes" in y:
print ("\n")
Start()
Work()
Again()
elif "no" in y:
pass
def Work():
if Action.startswith("pi"):
Cal.pi()
else:
pass
Start()
Work()
Again()
I am getting "Variable not defined only"
I am using Windows 7 and Python 3.3. What could be the possible issue?
You have to explicitely pass your "variables" to the functions that need them. You can read more about this in any programming tutorial (starting with Python's official tutorial). To "get" the variables from the function that sets them you have to return the variable(s). That's really CS101 BTW
As an exemple:
def foo(arg1, arg2):
print arg1, arg2
def bar():
y = raw_input("y please")
return y
what = "Hello"
whatelse = bar()
foo(what, whatelse)
More on this here: http://docs.python.org/2/tutorial/controlflow.html#defining-functions
Fixed version of your script (nb tested on Python 2.7 with a hack for input but should work as is on 3.x):
import math
def Start():
x = input("Please input what you want do to a number then the number; a whole number.\n(Example pi 2)\nYou can pow (pow 2 3; 2 to the power of 3),pi,square and cube: ").lower()
x = x.split()
Action = x[0]
number = int(x[1])
print ("Your number: " + str(number))
return (Action, number)
class Cal:
def pi(self, number):
print ("Your number multiplied by Pi: " + str(math.pi * number))
def Again():
y = input("Type 'Yes' to do another one if not type 'No': ").lower()
if "yes" in y:
print ("\n")
args = Start()
Work(*args)
Again()
elif "no" in y:
pass
def Work(Action, *args):
if Action.startswith("pi"):
Cal().pi(*args)
else:
pass
def Main():
args = Start()
Work(*args)
Again()
if __name__ == "__main__":
Main()
Inside your Start() function, put
global Action
That way, the variable will enter the global scope, so it will be visible from the other functions.
However, this is not good style. Rather, you should pass parameters to other functions instead of relying on global variables.