If loop is repeating itself when its not needed - python-3.x

I recently ran into a problem where the code would start repeating itself around line 69. I don't know why this is and any help would be amazing.
Here is the code.
import time
import threading
import random
totalviews = 0
videoViews = 0
totallikes = 0
videolikes = 0
totaldislikes = 0
videodislikes = 0
subscribers = 0
videolength = 0
midroles = 0
uploadTimer1 = 0
waitTimer1 = 0
x = 0
comadymins = 0
comadysecs = 0
def timer1():
global uploadTimer1
global waitTimer1
global x
time.sleep(.75)
if x == 1:
print(uploadTimer1, 'mins remaining')
uploadTimer1 -= 1
time.sleep(60)
if uploadTimer1 == 0:
x = 0
Timer1 = threading.Thread(target=timer1)
print('')
print("you decided to start a youtube channel")
while True:
time.sleep(1.25)
print('')
print('what type of video will you make')
print('1. comedy')
print('2. gaming')
print('3. science')
print('4. check timer')
UserInput = input('')
if UserInput == '1':
if waitTimer1 == 0:
comadymins = random.randint(10, 30)
comadysecs = random.randint(0, 60)
time.sleep(0.1)
print('video length will be', comadymins, ":", comadysecs)
time.sleep(1)
if comadymins <= 29 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
uploadTimer1 += 4
x += 1
Timer1.start()
waitTimer1 += 1
else:
print('okay')
if comadymins <= 19 and comadysecs <= 59:
print('would you like to upload now?')
time.sleep(.5)
UserInput = input('')
if UserInput == 'y':
print('video is uploading')
print('it will take 4 mins')
waitTimer1 += 1
uploadTimer1 += 4
x += 1
Timer1.start()
else:
print('okay')
else:
print('you already have a video running')
time.sleep(1)
if UserInput == '4':
print('okay')
print(uploadTimer1, "mins remaining")
any help would be amazing. I am also very new to coding so sorry if the code is messy or not to the average standards. I have only been coding for about a month and do it about 3 hrs a week if you have any recommendations that would be amazing.

your problem is, you have the same print data "would you like to upload now?" and two conditional statements that both act the same way.
you have a
if comadymins <= 29 and comadysecs <= 59:
and a
if comadymins <= 19 and comadysecs <= 59:
since you have a random number here:
comadymins = random.randint(10, 30)
something like "11" that is less than "19" and "29" at the same time so both of your conditions will fire and you will see the repeated sentence "would you like to upload now?".
you should work on the logic of your problem.
you may use elif for you second conditional statement to avoid firing in case of first statement was true, or choose a range without overlap.
try this for your first if statement:
if 19<comadymins <= 29 and comadysecs <= 59:

You have an infinite loop when you state while True:
This will run through all lines underneath it forever.
You could exit this loop by adding a break inside the loop if a certain condition is met.

Related

Number Guessing game Computer Playing

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 ')

How do I add a score to this game

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

Python Error handling for an input requiring a integer

I would like to implement error handling so that if the user puts in anything besides an integer they get asked for the correct input. I believe try/except would work but I am wondering how I can get it to check for both a correct number within a range and ensuring there are no other characters. I have pasted my code below for review.
Thanks!
# Rock Paper Scissors
import random as rdm
print("Welcome to Rock/Paper/Scissors, you will be up against the computer in a best of 3")
# game_counter = 0
human_1 = input("Please enter your name: ")
GameOptions = ['Rock', 'Paper', 'Scissors']
hmn_score = 0
cpt_score = 0
rps_running = True
def rps():
global cpt_score, hmn_score
while rps_running:
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
while not int(hmn) in range(0, 3):
hmn = int(input("""Please select from the following:
1 - Rock
2 - Paper
3 - Scissors
\n""")) - 1
print('You Chose: ' + GameOptions[hmn])
cpt = rdm.randint(0, 2)
print('Computer Chose: ' + GameOptions[cpt] + '\n')
if hmn == cpt:
print('Tie Game!')
elif hmn == 0 and cpt == 3:
print('You Win')
hmn_score += 1
elif hmn == 1 and cpt == 0:
print('You Win')
hmn_score += 1
elif hmn == 2 and cpt == 1:
print('You Win')
hmn_score += 1
else:
print('You Lose')
cpt_score += 1
game_score()
game_running()
def game_score():
global cpt_score, hmn_score
print(f'\n The current score is {hmn_score} for you and {cpt_score} for the computer \n')
def game_running():
global rps_running
if hmn_score == 2:
rps_running = False
print(f"{human_1} Wins!")
elif cpt_score == 2:
rps_running = False
print(f"Computer Wins!")
else:
rps_running = True
rps()
To answer your question, you can do something like the following
options = range(1, 4)
while True:
try:
choice = int(input("Please select ...etc..."))
if(choice in options):
break
raise ValueError
except ValueError:
print(f"Please enter a number {list(options)}")
print(f"You chose {choice}")
As for the a code review, there's a specific stack exchange for that, see Code Review

Consecutive Coin Count

Program runs and stops after conditions are met. I need the program to stop after 3 consecutive heads are flipped. How can this be done?
import random
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
print("heads")
sum_heads += 1
else:
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
flips()
You can add a counter for consecutive heads that turns back to 0 in case the next is tail.
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
consecutive = 0
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
print("heads")
consecutive+=1
if consecutive==3:
print("Simulation complete! 3 consecutive heads were flipped.")
break
sum_heads += 1
else:
consecutive = 0
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
I tried to keep it as simple as possible. You can try this.
import random
def flips():
"""Coin flip simulation."""
# sum of coins
sum_heads = 0
sum_tails = 0
last_3_results = []
# Simulation
while True:
coin = random.randint(0,1)
if coin == 0:
sum_heads += 1
print("heads")
else:
print("tails")
sum_tails += 1
if sum_heads == 8:
print("Simulation complete! 8 total heads were flipped.")
break
if sum_tails == 9:
print("Simulation complete! 9 total tails were flipped.")
break
last_3_results.append(coin)
if len(last_3_results) > 3:
last_3_results.pop(0)
if len(last_3_results) ==3 and len(set(last_3_results)) == 1 and last_3_results[0] == 0:
break
# Ask user for repeat
result = input("Would you like to run the simulation again (yes/no)? ").lower()
while result == "yes":
flips()
break
flips()

I can't figure it out why it doesn't print after the line of code ( if 6 <= n <= 20 )

I am running this code . and when i put the input as 6 or greater it dosent print anything and also dont show any error . like it doesnt print anything on and after that if 6 <= n <= 20
i tried rewritng the code or bugs and i checked it througly many times .
#!/bin/python3
import math
import os
import random
import re
import sys
if __name__ == '__main__':
n = int(input().strip())
if n%2 == 0 :
if 2 <= n <= 5:
print("Not Weird")
elif n%2 == 0:
if 6 <= n <= 20 :
print("Weird")
elif n%2 == 0:
if n > 20:
print("Not Weird")
else:
print("Weird")
It doesnt show any error
Try the following:
if __name__ == '__main__':
n = int(input().strip())
if n%2 == 0 :
if 2 <= n <= 5:
print("Not Weird")
elif 6 <= n <= 20 :
print("Weird")
elif n > 20:
print("Not Weird")
else:
print("Weird")
You are not using using if properly. Check this,
if __name__ == '__main__':
n = int(input().strip())
if n%2 == 0 :
if 2 <= n and n <= 5:
print("Not Weird")
elif 6 <= n and n <= 20 :
print("Weird")
elif n > 20:
print("Not Weird")
else:
print("Weird")
What is the mistake in your code?
ANS:
if n%2 == 0:
some condition
elif n%2 ==0:
some condition
Your both if and elif conditions are same. So, it never execute elif condition.
So, in your case when n=6, it goes into 1st if condition. As there is no any else statement in your 1st if condition. It won't print anything as expected.

Resources