I'm new to coding in Python and I starting writing my own program. Things don't work and I'm having great difficulty understanding why.
I've tried changing my variables from global to class to everything under the sun and it's still bugs. I've also went through my code many many times but I kind of feel as if I'm just throwing together random things.
This code is supposed to ask for your name then ask for your height, weight, shape-size and shoe-size. It should have a function for each variable which asks the user for their information then at the end of the code it should state that persons name then state their other information back to them. ex
hello Jimmy! Your Height is 5'6" your weight is 180 lbs your shirt-size is medium and your shoe-size is 10.
My code:
name = input('What Is your Name?')
print('Hello' + name + '!')
# This is the next part in the code
class Information:
global name1
name1 = Information()
height2 = Information()
weight3 = Information()
shirtSize4 = Information()
shoeSize5 = Information()
n = name1
h = height2
w = weight3
sh = shirtSize4
ss = shoeSize5
i=int
def n() : (h,w,sh,ss)
def h(): int(input('Please Enter Your Height'))
if h == i(4):
print("Please provide a Height larger than 4 feet")
else:
print(h)
def w() : i(input("Please Enter Your Weight in number of pounds, ex(100)"))
if w == i(90):
print("There is now way you're under 90 lbs. Please Enter A different weight")
def sh() : i(input("Please Enter your Shirt Size"))
def ss() : i(input("Please enter Your shoe size"))
if ss == i(3):
print('Please Enter a shoe size larger than an infant thank you.')
else:
print(ss)
#in the next line i'm trying to print out a string with variables
def print():
("Hello" + n + '! Your Height is' + h + "Your Weight is" + w + "Your Shirt-Size is"+ sh + "and your ShoeSize is" + ss)
And the result:
What Is your Name?Zack
HelloZack!
<function h at 0x02D09C48>
<function ss at 0x02D09D20>
Process finished with exit code 0
This is what comes up instead of input questions.
Related
So I tried to make a game where the computer chooses a random 4 digit number out of 10 given numbers. The computer then compares the guess of the user with the random chosen code, and will give feedback accordingly:
G = correct digit that is correctly placed
C = correct digit, but incorrectly placed
F = the digit isn't in the code chosen by the computer
However, the feedback doesn't always output correctly.
Fox example, when I guess 9090, the feedback I get is F C F, while the feedback should consist of 4 letters.... How can I fix this?
#chooses the random pincode that needs to be hacked
import random
pincode = [
'1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301', '1022'
]
name = None
#Main code for the game
def main():
global code
global guess
#Chooses random pincode
code = random.choice(pincode)
#Sets guessestaken to 0
guessesTaken = 0
while guessesTaken < 10:
#Makes sure every turn, an extra guess is added
guessesTaken = guessesTaken + 1
#Asks for user input
print("This is turn " + str(guessesTaken) + ". Try a code!")
guess = input()
#Easteregg codes
e1 = "1955"
e2 = "1980"
#Checks if only numbers have been inputted
if guess.isdigit() == False:
print("You can only use numbers, remember?")
guessesTaken = guessesTaken - 1
continue
#Checks whether guess is 4 numbers long
if len(guess) != len(code):
print("The code is only 4 numbers long! Try again!")
guessesTaken = guessesTaken - 1
continue
#Checks the code
if guess == code:
#In case the user guesses the code in 1 turn
if (guessesTaken) == 1:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turn!")
#In cases the user guesses the code in more than 1 turn
else:
print("Well done, " + name + "! You've hacked the code in " +
str(guessesTaken) + " turns!")
return
#Sets empty list for the feedback on the user inputted code
feedback = []
nodouble = []
#Iterates from 0 to 4
for i in range(4):
#Compares the items in the list to eachother
if guess[i] == code[i]:
#A match means the letter G is added to feedback
feedback.append("G")
nodouble.append(guess[i])
#Checks if the guess number is contained in the code
elif guess[i] in code:
#Makes sure the position of the numbers isn't the same
if guess[i] != code[i]:
if guess[i] not in nodouble:
#The letter is added to feedback[] if there's a match
feedback.append("C")
nodouble.append(guess[i])
#If the statements above are false, this is executed
elif guess[i] not in code:
#No match at all means an F is added to feedback[]
feedback.append("F")
nodouble.append(guess[i])
#Easteregg
if guess != code and guess == e1 or guess == e2:
print("Yeah!")
guessesTaken = guessesTaken - 1
else:
print(*feedback, sep=' ')
main()
You can try the game here:
https://repl.it/#optimusrobertus/Hack-The-Pincode
EDIT 2:
Here, you can see an example of what I mean.
Here is what I came up with. Let me know if it works.
from random import randint
class PinCodeGame(object):
def __init__(self):
self._attempt = 10
self._code = ['1231', '9997', '8829', '6765', '9114', '5673', '0103', '4370', '8301',
'1022']
self._easterEggs = ['1955', '1980', '1807', '0609']
def introduction(self):
print("Hi there stranger! What do I call you? ")
player_name = input()
return player_name
def show_game_rules(self):
print("10 turns. 4 numbers. The goal? Hack the pincode.")
print(
"For every number in the pincode you've come up with, I'll tell you whether it is correct AND correctly placed (G), correct but placed incorrectly (C) or just plain wrong (F)."
)
def tutorial_needed(self):
# Asks for tutorial
print("Do you want a tutorial? (yes / no)")
tutorial = input().lower()
# While loop for giving the tutorial
while tutorial != "no" or tutorial != "yes":
# Gives tutorial
if tutorial == "yes":
return True
# Skips tutorial
elif tutorial == "no":
return False
# Checks if the correct input has been given
else:
print("Please answer with either yes or no.")
tutorial = input()
def generate_code(self):
return self._code[randint(0, len(self._code))]
def is_valid_guess(self, guess):
return len(guess) == 4 and guess.isdigit()
def play(self, name):
attempts = 0
code = self.generate_code()
digits = [code.count(str(i)) for i in range(10)]
while attempts < self._attempt:
attempts += 1
print("Attempt #", attempts)
guess = input()
hints = ['F'] * 4
count_digits = [i for i in digits]
if self.is_valid_guess(guess):
if guess == code or guess in self._easterEggs:
print("Well done, " + name + "! You've hacked the code in " +
str(attempts) + " turn!")
return True, code
else:
for i, digit in enumerate(guess):
index = int(digit)
if count_digits[index] > 0 and code[i] == digit:
count_digits[index] -= 1
hints[i] = 'G'
elif count_digits[index] > 0:
count_digits[index] -= 1
hints[i] = 'C'
print(*hints, sep=' ')
else:
print("Invalid input, guess should be 4 digits long.")
attempts -= 1
return False, code
def main():
# initialise game
game = PinCodeGame()
player_name = game.introduction()
print("Hi, " + player_name)
if game.tutorial_needed():
game.show_game_rules()
while True:
result, code = game.play(player_name)
if result:
print(
"Oof. You've beaten me.... Do you want to be play again (and be beaten this time)? (yes / no)")
else:
print("Hahahahaha! You've lost! The correct code was " + code +
". Do you want to try again, and win this time? (yes / no)")
play_again = input().lower()
if play_again == "no":
return
main()
I am going to write a guessing game with the computer.
I choose one number in my head and the Computer is going to find it out, and it can guess between a range.
The problem is I don’t know how can I update this range during the program run.
import random
x = 1
y = 99
guess= random.randint(x,y)
print(guess)
play='true'
while play=='true':
a=x
b=y
results = input()
if results == 'd':
play='false'
else:
if results == 'b':
a=guess
print('My number is bigger!')
newguess= random.randint(a,b)
print (newguess)
elif results == 'k':
b=guess
print('My number is smaller!')
newguess= random.randint(a,b)
print (newguess)
print ('Wooow , computer you did it! ')
Sorry about all the explanations in the code but this is a version of the game that I did a while ago. What I did was I wanted to shrink the guessing range each time the user said high or low. e.g. if the computer chooses 50, and the user says 'High' then the program will not chose a number greater than 50, the same applies for 'Low". Enjoy
import random
count = 0 #Number of attemps. how many times while loop runs.
guess = random.randint(1,100)#The guess generator
(l,u) = (0,100)
lower_guess = l
upper_guess = u
n = 0
print('Chose a number between ', l, ' and ', u , '.' )
#The game. These are outside the function so that they don't print in every loop because they are unwanted for some Y inputs.
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')#User states
#The function
while n != 'guess':
count +=1 #adds 1 to count each time loop runs
if Y == 'L':
lower_guess = guess+1
guess = random.randint(lower_guess , upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'H':
upper_guess = guess - 1
guess = random.randint(lower_guess, upper_guess)#Redifining guess to eliminate irrelevant guesses from the range
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
elif Y == 'Y':
print('I guessed it in ' + str(count) + ' attempts')
break
else:
count = 0
lower_guess = l
upper_guess = u
guess = random.randint(1,100)
print('That input was invalid. The game has restarted.')
print('You can chose a new number or keep your old one.')
print('Is it ' + str(guess))
Y = input('Low = L, High = H and Yes = Y:')
I am having difficulty keeping a track of the total number of inputs. I want my program to keep track of the total number of inputs and print it when my while loop breaks. Any help is appreciated!
r = float(input("enter r:"))
def main(r):
a = 3.14 * (float(r ** 2))
s_v = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
total += r
print("Total = " , total)
break
else:
print("Area = ", a)
continue
main(r)
I assume that you want your program to re-calculate the area with each iteration. As written, it will only be calculated the first time you run the mymian function. You don't need to pass any arguments to the function.
def mymian():
sentinal_value = 0
total = 0
while True:
r = float(input("enter r:"))
if r == sentinal_value:
print("Total number of r provided to this program" , total)
break
else:
print("Area = ", 3.14 * (float(r ** 2)))
total += 1
continue
I'm in my 3rd week of a required college programming course. I was given an assignment to calculate BMI. I can write code that produces the desired output, but the instruction say I must use functions and that is giving me trouble. Here is the code I have come up with and I believe that maybe my issue is that on lines 12, 16, and 20, the input value is not being stored in the function name. Also something else seems to be wrong because when I run it, it asks for the student height twice. If someone could look at this and give me some direction I would really appreciate it.
Instructions...
You are the nutritional coach for a local high school football team. You realize that some of the players are not up to par having returned from summer break. Realizing nutrition plays a key in a productive team, you decide to implement a Body Mass Index Program.
Write a modularized Body Mass Index (BMI) Program which will calculate the BMI of a team player. The formula to calculate the BMI is as follows:
BMI = Weight *703 / Height^2
Note: Height^2 means, the value of Height raised to the power of 2.
Your program should utilize the following functions:
A method to obtain the weight of a player
A method to obtain the height of a player
A method to calculate the BMI of a player
A method to display the height, weight, and calculated BMI
import math
import sys
print("King's BMI Calculator")
while True:
name = input("Please enter student's name or press 0 to quit:")
if name == "0":
break
def h():
height = int(input("Please enter student's height in inches:"))
return height
def w():
weight = int(input("Please enter student's weight in pounds:"))
return weight
def bmi():
total = float((str(w() * 703)/str(h() * str(h()))))
return total
def printbmi():
print(name + "'s BMI Profile")
print("Height:", str(h(), "inches"))
print("Weight:", str(w(), "lbs"))
print("BMI Index:" + str(float(round(bmi(), 1))))
return
def main():
h()
w()
printbmi()
main()
Whenever you call a function (i.e. function_name()), the function is executed. Therefore, your script will ask for input whenever w() or h() is called. A simple solution would be to store the return value to a variable, maybe to weight = w() and height = h() so that you can use the variables when needed instead of calling the entire function every time.
def w():
# ...
return weight
def h():
# ...
return height
def bmi(w, h)
# ...
return total
def printbmi(w, h, total):
# print(w, h, total)
def main():
# prompt
weight = w()
height = h()
total = bmi(weight, height)
printbmi(weight, height, total)
while True:
main()
You can update your code by considering the followings.
Define the functions (h(),w(),bmi()) outside the while loop.
Don't call h() and w() inside main() because you are calling them inside printbmi(). So, your program will ask for input twice for each student.
You should move the main() function outside the loop as well.
You have problem in your printbmi() and bmi() functions as well. You are calling the h() and w() functions many times.
You can update your code as follows.
import math
import sys
def h():
height = int(input("Please enter student's height in inches: "))
return height
def w():
weight = int(input("Please enter student's weight in pounds: "))
return weight
def bmi(height, weight):
total = float((weight * 703)/(height * height))
return total
def printbmi(name):
print(name + "'s BMI Profile")
height = h()
print("Height:", str(height), "inches")
weight = w()
print("Weight:", str(weight), "lbs")
print("BMI Index:" + str(float(round(bmi(height, weight), 1))))
def main(name):
printbmi(name)
print("King's BMI Calculator")
while True:
name = input("Please enter student's name or press 0 to quit:")
if name == "0":
break
else:
main(name)
It outputs:
King's BMI Calculator
Please enter student's name or press 0 to quit:Jack
Jack's BMI Profile
Please enter student's height in inches: 12
Height: 12 inches
Please enter student's weight in pounds: 16
Weight: 16 lbs
BMI Index:78.1
Please enter student's name or press 0 to quit:0
import random
def diceRoll(number):
roll = random.randint(1,number)
print("Rolling a ",number," sided die.")
return roll
def newAccount(playername):
print("Greetings ", playername,"! We'll generate your charecter's attributes by rolling some die")
skillroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
strengthroll = 10 + (int(round((diceRoll(12)/diceRoll(4)))))
print("You have ",skillroll," skillpoints and ",strengthroll," strength!")
class newplayer:
name = playername
skill = skillroll
strength = strengthroll
save(newplayer)
def save(newplayer):
"""Saves all details"""
file = open("accounts.txt","a")
file.write("CharacterName = '" + newplayer.name + "'\n")
file.write("Strength = " + str(newplayer.strength) + '\n')
file.write("Skill = " + str(newplayer.skill) + '\n')
file.write("\n")
print("Saved account")
def newPlayer():
try:
player1 = input("What is your 1st player's name? ")
newAccount(player1)
except:
print("Please only enter letters for your character name ")
newPlayer()
newPlayer()
print(" ")
player2 = input("What is your 2nd player's name? ")
newAccount(player2)
The part in bold is the part of the code I have attempted to alter to add some sort of error handling. Someone help me out here please, I know it's probably simple but I can't find an answer to this question anywhere.
Pythons RegEx would be a quite easy solution:
import re
if not re.match("[a-z]+$",inputString):
#your exception handling