import time
total = 0
pos = 0
zeroes = 0
neg = 0
print('This program will add any seven numbers for you')
time.sleep(2)
print()
a = int(input('Please enter the first number: '))
total = total + a
if a > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0:
zeroes = zeroes + 1
elif a < 0:
neg = neg + 1
time.sleep(2)
c = int(input('Please enter the third number: '))
total = total + c
if c > 0:
pos = pos + 1
elif c == 0:
zeroes = zeroes + 1
elif c < 0:
neg = neg + 1
time.sleep(2)
d = int(input('Please enter the fourth number: '))
total = total + d
if d > 0:
pos = pos + 1
elif d == 0:
zeroes = zeroes + 1
elif d < 0:
neg = neg + 1
time.sleep(2)
e = int(input('Please enter the fifth number: '))
total =total + e
if e > 0:
pos = pos + 1
elif e == 0:
zeroes = zeroes + 1
elif e < 0:
neg = neg + 1
time.sleep(2)
f = int(input('Please enter the sixth number: '))
total = total + f
if f > 0:
pos = pos + 1
elif f == 0:
zeroes = zeroes + 1
elif f < 0:
neg = neg + 1
time.sleep(2)
g = int(input('Please enter the seventh number: '))
total = total + g
if g > 0:
pos = pos + 1
elif g == 0:
zeroes = zeroes + 1
elif g < 0:
neg = neg + 1
time.sleep(2)
print()
print('The sum of your entries is: ', + total)
time.sleep(2)
print()
print('You entered', + pos, 'positive numbers')
time.sleep(2)
print()
print('You entered', + zeroes, 'zeroes')
time.sleep(2)
print()
print('You entered', + neg, 'negative numbers')
print()
time.sleep(3)
Hello! I have the variable 'neg' keeping a running total of all of the negative numbers that the user enters. It seems as if the negative numbers aren't always being added to the 'neg' running total at the end of the code.
I've been working with Python 3x for about a week now, so be gentle :)
Thanks in advance for the help!
Edit: I have reworked this into a (working) loop per the advice of Kevin, is this a good loop? It seems to work, I'm just looking for pointers as I'm kind of struggling with Python logic. Big thanks to Kevin, wish I could upvote you!
New code posted below:
import time
sums = 0
pos = 0
neg = 0
zero = 0
numb = 0
user_numb = 0
running = True
print('This program will add any 7 numbers for you')
time.sleep(.5)
print()
while running:
user_numb = int(input('Please enter a number: '))
sums = user_numb + sums
numb = numb + 1
print()
if user_numb > 0:
pos = pos + 1
elif user_numb < 0:
neg = neg + 1
elif user_numb == 0:
zero = zero + 1
if numb == 7:
running = False
print()
time.sleep(2)
print('The sum of the numbers entered was: ', + sums)
print()
time.sleep(2)
print('You entered', + pos, 'positive numbers')
print()
time.sleep(2)
print('You entered', + neg, 'negative numbers')
print()
time.sleep(2)
print('You entered', + zero, 'zeroes')
print()
print()
time.sleep(3)
In the section with b you forgot in the copy/pasted code to change all 'a' into 'b' and have still twice an 'a' there:
b = int(input('Please enter the second number: '))
total = total + b
if b > 0:
pos = pos + 1
elif a == 0: # CHANGE TO 'b'
zeroes = zeroes + 1
elif a < 0: # CHANGE TO 'b'
neg = neg + 1
so you see wrong results only in case the second number is a 0 or negative.
Related
I have created this game. User is giving a number from 1 to 100. Computer is trying to guess it. User is giving hint to computer to go lower or go higher. I am open for any feedback.
Thank you in advance.
import os
import random
os.system('clear')
user = int(input("Please enter a number between 1-100: "))
print("Your Number is: " + str(user))
comp_list = list(range(1,101))
comp_selection = random.choice(comp_list)
count = 0
def game(num, a = 1, b = 100):
global count
print("I have chosen " + str(num) + "\nShould I go Higher or Lower or Correct? ")
user = input("Your Selection: ")
if user == "L":
count = count + 1
low_game(a, num)
elif user == "H":
count = count + 1
high_game(num, b)
else:
print("I have guessed correctly in " + str(count) + " tries")
def low_game(old_low, new_High):
x = new_High
new_comp_list = list(range(old_low, x))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection, old_low, x)
def high_game(new_low, old_high):
x = new_low + 1
new_comp_list = list(range(x, old_high))
new_comp_selection = random.choice(new_comp_list)
game(new_comp_selection,x, old_high)
game(comp_selection)
I agree, you have over complicated the game with recursive functons.
Here is a much simplified game with penalties for player who does not answer correctly
or falsifies the answer:)
import sys, random
wins = 0
loss = 0
while 1:
user = input('Please enter a number between 1-100: (return or x = quit) > ' )
if user in [ '', 'x' ]:
break
elif user.isnumeric():
user = int( user )
if user < 1 or user > 100:
sys.stdout.write( 'Number must be between 1 and 100!!\n' )
else:
low, high, count = 1, 100, 0
while 1:
p = random.randint( low, high )
count += 1
while 1:
answer = input( f'Is your number {p}? Y/N > ').upper()
if answer in [ 'Y','N' ]:
break
else:
sys.stderr.write( 'Answer must be Y or N\n' )
if answer == 'N':
if p != user:
if input( f'Is my number (H)igher or (L)ower? > ').upper() == 'H':
if user < p:
high = p - 1
else:
sys.stderr.write( f'Wrong!! Your number was lower. You loss\n' )
loss =+ 1
break
else:
if user > p:
low = p + 1
else:
sys.stderr.write( f'Wrong!! Your number higher. You loss\n' )
loss =+ 1
break
else:
sys.stderr.write( f'Cheat!! Your number is {user}!! You loss\n')
loss =+ 1
break
else:
if user == p:
sys.stdout.write( f'I guessed Correctly in {count} guesses\n' )
wins += 1
else:
sys.stderr.write( f'Cheat!! This is not your number. You loss\n' )
loss =+ 1
break
print( f'Computer won = {wins} : You lost = {loss}' )
Happy coding.
You have really overly complicated the problem. The basic process flow is to have the computer guess a number within a fixed range of possible numbers. If the guess is incorrect, the user tells the computer how to adjust the list by either taking the guessed number as the low end or the high end of the guessing range. So to accomplish this, I would do the following:
from random import randint
# Function to request input and verify input type is valid
def getInput(prompt, respType= None):
while True:
resp = input(prompt)
if respType == str or respType == None:
break
else:
try:
resp = respType(resp)
break
except ValueError:
print('Invalid input, please try again')
return resp
def GuessingGame():
MAX_GUESSES = 10 # Arbritray Fixed Number of Guesses
# The Game Preamble
print('Welcome to the Game\nIn this game you will be asked to provide a number between 1 and 100 inclusive')
print('The Computer will attempt to guess your number in ten or fewer guesses, for each guess you will respond by telling the computer: ')
print('either:\n High - indicating the computer should guess higher\n Low - indicating the computer should guess lower, or')
print(' Yes - indicating the computer guessed correctly.')
# The Game
resp = getInput('Would You Like To Play?, Respond Yes/No ')
while True:
secret_number = None
if resp.lower()[0] == 'n':
return
guess_count = 0
guess_range = [0, 100]
secret_number = getInput('Enter an Integer between 1 and 100 inclusive', respType= int)
print(f'Your secret number is {secret_number}')
while guess_count <= MAX_GUESSES:
guess = randint(guess_range[0], guess_range[1]+1)
guess_count += 1
resp =getInput(f'The computer Guesses {guess} is this correct? (High?Low/Yes) ')
if resp.lower()[0] == 'y':
break
else:
if resp.lower()[0] == 'l':
guess_range[1] = guess - 1
else:
guess_range[0] = guess + 1
if guess == secret_number:
print (f'The Computer has Won by Guessing your secret number {secret_number}')
else:
print(f'The Computer failed to guess your secret number {secret_number}')
resp = getInput('Would You Like To Play Again?, Respond Yes/No ')
I've been trying to figure out how to add a score to this for ages. I'm still not sure ;( sorry I'm new to coding.
this is the code for the main part
while roundsPlayed > 0:
chips_left = MAX_CHIPS
n = 1
rounds = 1
while chips_left > 0:
while True:
print("Number of chips left {}".format(chips_left))
if n%2 == 0:
print("{} How many chips would you like to take (1 - 3): ".format(playerTwo))
else:
print("{} How many chips would you like to take (1 - 3): ".format(playerOne))
try:
chipsTaken = int(input())
if chipsTaken < 1 or chipsTaken > 3:
print("Please enter a valid number from 1 to 3!")
else:
break
except:
print("Thats not even a number brotherman")
n += 1
chips_left = chips_left - chipsTaken
roundsPlayed = roundsPlayed - 1
rounds += 1
I am trying to get the below code to run in Python and I keep getting a error at the return n point. Can someone please look at the code and see where I messed up at?
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
def main():
average = 0
count = 0
while(True):
name = input("Please enter a student name or '*' to finish: ")
if name == '*':
break
scores = 0
scores += getPosFloat('Please enter a score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
scores += getPosFloat('Please enter another score for ' + name + ': ', 0, 100)
print('The average score for ' + name+ ' is: %.2f' % (scores/3))
#please give the proper argument
average += getPosFloat('Please enter average score for ' + name + ': ', 0, 100)
count += 1
if count!=0:
print("The class average is: ",(average)/count)
main()
You can't return a value outside a function. (I'm assuming that is all the code you have since that is all you provided )
You are missing your function definition. It looks like you should have
def getPosFloat(prompt, n1, n2):
while True:
n = input(prompt)
try:
n = float(n)
if n < n1 or n > n2:
print('Error. Input was out of range')
else:
break
except:
print('Error. Please enter a number')
return n
before your main() There are still other errors, but that will get you started
I can't figure out what I am doing wrong. I have tried using a break, and tried setting what the variable !=, I am doing this on cengage and it is very finnicky.
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
while leftOrRight != "X":
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
your input() is outside the while loop, so leftOrRight never changes, never get to X so it will not exit the loop:
leftOrRight = None
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
According to your code you are not changing the value for leftOrRight after entering the loop so the condition for your while loop is never false I would suggest the following edit:
""" LeftOrRight.py - This program calculates the total number of left-handed and right-handed students in a class. Input: L for left-handed; R for right handed; X to quit. Output: Prints the number of left-handed students and the number of right-handed students."""
rightTotal = 0 # Number of right-handed students.
leftTotal = 0 # Number of left-handed students.
leftOrRight = '' #anything random
while leftOrRight != "X":
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
print (leftOrRight)
if leftOrRight == "L":
leftTotal = (leftTotal + 1)
elif leftOrRight == "R":
rightTotal = (rightTotal + 1)
else:
break
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
so that you get a prompt every time the loop is executed and you can click X to exit
Your program just got the character that had the largest id in the ascii table.
And only doing the first string as the longString = max(n) wasn't even in the while loop.
also max returns the largest value, so in this case it was just converting the text into an ascii number.
instead you should use len(string) which returns the length of the string.
Unlike max() which is used like:
11 == max(11,10,1,2) as 11 is the largest character.
n = (input("Input: ")) #get initial input
longest = 0 #define the varible which we will keep the length of the longest string in
longest_str = "" #define the varible which stores the value of the longest string.
while n: #you don't need that other stuff, while n does the same as while n != ''
n = str(input("Input: ")) #get input
length = len(n) #gets the length of the input
if length > longest: #if the length of our input is larger than the last largest string
longest = length #set the longest length to current string length
longest_str = n #set the longest string to current string
#once the user hits enter (typing "") we exit the while loop, and this code runs afterwards.
print("Longest input was", longest_str, "at", longest, "characters long")
Because there are two specific counts we are accumulating for, and the outlying char is at the end of our input, we can set our while to True to break when we hit a char other that "L" or "R".
leftOrRight = ""
# Write your loop here.
while True:
leftOrRight = input("Enter an L if you are left-handed,a R if you are right-handed or X to quit.")
if leftOrRight == "L":
leftTotal = leftTotal + 1
elif leftOrRight == "R":
rightTotal = rightTotal + 1
else:
break
# Output number of left or right-handed students.
print("Number of left-handed students: " + str(leftTotal))
print("Number of right-handed students: " + str(rightTotal))
I've just started to learn python and I've decided to try and do a bubble sort. I've used the code below which works ok if the numbers to be sorted are 0 to 9. After that, it doesn't sort them correctly. I think, in my limited knowledge that this is because it is a 'list'.
I would like the user to be able to input the numbers but for the program to sort them regardless of the length of the number. Any help would be appreciated.
def bubble_sort(items):
changes=0
for i in range(len(items)):
for j in range(len(items)-1-i):#-i = optimised??
if items[j] > items[j+1]:
items[j], items[j+1] = items[j+1], items[j] # Swap
changes=changes+1
print(items)
print("Number of passes =",i)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers=input()
items=numbers.split()
Try this:
print('welcome to the automatic bubble sorter')
inputted_list = input('please enter a list of numbers seperated by commas: ')
list = inputted_list.split(',')
number_of_items = int(len(list))
sorting_method = input('if you would like your list to be sorted in ascending order, press 1, if you would like it to be sorted in descending order, press 2')
print(list)
if sorting_method == '1':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
counter2 = 0
permanent_numbers = []
while number_of_swaps > 0:
counter2 = counter2 + 1
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
permanent_numbers.append(list[number_of_items - counter2])
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
elif sorting_method == '2':
position = 0
Pass = 0
counter = 1
while counter == 1:
number_of_swaps = 1
while number_of_swaps > 0:
number_of_swaps = 0
while position < number_of_items - 1:
if int(list[position]) > int(list[position + 1]):
number_of_swaps = number_of_swaps + 1
item1 = int(list[position])
item2 = int(list[position + 1])
list[position] = item2
list[position + 1] = item1
position = position + 1
Pass = Pass + 1
print('pass',Pass,':',list)
position = 0
if Pass == number_of_items - 1:
number_of_swaps = 0
if number_of_swaps == 0:
counter = 0
print('total number of passes:', Pass)
try map:
I suggested using map before, but I just remembered that map in python 3.x* yields a generator rather than a list, so that is why you cannot take the length of it. The updated answer is below
numbers = input("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
items = [int(num) for num in numbers.split()]
Modified existing code:
#!/usr/bin
def bubble_sort(items):
changes = passes = 0
last = len(items)
swapped = True
while swapped:
swapped = False
passes += 1
for j in range(1, last):
if items[j - 1] > items[j]:
items[j], items[j - 1] = items[j - 1], items[j] # Swap
changes += 1
swapped = True
last = j
print(items)
print("Number of passes =",passes)
print("Number of swaps =",changes)
print("Welcome to a Bubble Sort Algorithm in Python!")
while True:
print("Enter as many numbers as you want.\n You can choose between 0 and 9.\nLeave a space between each one")
numbers = input()
items = [int(num) for num in numbers.split() if num.isdigit()]
if items: bubble_sort(items)
def b_sort(list):
for iter_num in range(len(list)-1,0,-1):
for idx in range(iter_num):
if list[idx] > list[idx+1]:
temp = list[idx]
list[idx] = list[idx+1]
list[idx+1] = temp
str_input= input("Enter numbers: ")
list = [int(x) for x in str_input.split()]
b_sort(list)
print('sorted elements are: ')
print(list)
def sort():
try:
n = [1,8,6]
l = len(n)
print("Original list:", n)
for i in range(l - 1):
for j in range(0,l - i - 1):
if n[j] > n[j + 1]:
n[j], n[j + 1] = n[j + 1], n[j]
print("List after sorting is:", n)
except:
print("Error in inputing values")
sort()