a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive " + a)
else:
print("You can't drive " + a + " You are underage")
i want to print only first name here, so if given name is Don Jon then the output should be "You can drive Don" or You can't drive Don You are underage
You need:
a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive ", a.split()[0])
else:
print("You can't drive " , a.split()[0]," You are underage")
You can also use str.find()
a = input("Enter your Full Name ")
b = int(input("Enter your age "))
if b >= 20:
print("You can drive ", a[:a.find(" ")])
else:
print("You can't drive " , a[:a.find(" ")]," You are underage")
Related
So I'm refreshing what little I knew of Python before and playing around with some beginner projects. I'm toying arond with it now, and I'm just trying to learn and see what I can do. I made a "Guessing Game" and turned it into a function. I want to store these reults in a list each time it is used. I want the results to automatically go to the list when the game is completed and then to be able to print the list when desired.
I'm not sure if I need to create a new function for this, or if I should be creating this within my current "guessing_game" function. I've tried to create a list previously, but I'm not sure how to create and store the variable of the game result in order to add it into the list. I feel like this is probably a fairly simple problem, so I apologize if this is a dumb question.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name ")
number_of_guesses = 0
print('Howdy' + player_name + "Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(guessing_game())
You can create a list inside of the function, and then everytime they guess, you can store the guess inside the list. At the end, we can print the list.
def guessing_game():
import random
number = random.randint(1, 1000)
player_name = input("Enter name: ")
number_of_guesses = 0
guesses = []
print('Howdy ' + player_name + " Guess a number between 1 and 1000: ")
while number_of_guesses < 10:
guess = int(input())
guesses.append(guess)
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
else:
print(" Well, yer were close, Stofe. Shoulda guessed " + str(number))
print("These were the numbers you guessed:")
for g in guesses:
print(g)
print(guessing_game())
What you need to do is create a list with something like val = []. I added it into the code and also added a formatting piece so it looks nice.
def guessing_game():
import random
guesses = []
number = random.randint(1, 1000)
guess = number / 2
player_name = input("Enter name ")
number_of_guesses = 0
print(f'Howdy {player_name}. Guess a number between 1 and 1000: ')
while number_of_guesses < 10:
guess = int(input('> '))
guesses = guesses + [guess]
number_of_guesses += 1
if guess < number:
print("Too Low, Joe")
if guess > number:
print("Too high, Sly")
if guess == number:
break
formatted_guesses = ''
for _ in range(len(guesses)):
if _ != len(guesses) - 1:
formatted_guesses = formatted_guesses + str(guesses[_]) + ', '
else:
formatted_guesses = formatted_guesses + str(guesses[_]) + '.'
if guess == number:
print("You got it, Bobbit, in " + str(number_of_guesses) + " tries")
print(f'You guessed {formatted_guesses}')
else:
print("Well, yer were close, Stofe. Shoulda guessed " + str(number))
print(f'You guessed {formatted_guesses}')
guessing_game()
Hey I'm trying to add a variable for "won" or "loss", I already have a variable for players name and guesses allowed.
Any help would be kind thanks. This is the code I have so far:
import random
number = random.randint(1, 100)
player_name = input("Hello, What's your name?: ")
number_of_guesses = 0
print("Okay! "+ player_name+ " I am guessing a number between 1 and 100:")
max_guesses = random.randint(1, 6)
print("You have " + str(max_guesses) + " guesses. ")
while number_of_guesses < max_guesses:
guess = int(input())
number_of_guesses += 1
if guess < number:
print("Your guess is too low")
if guess > number:
print("Your guess is too high")
if guess == number:
break
if guess == number:
print("You guessed the number in " + str(number_of_guesses) + " tries!")
else:
print("You did not guess the number, the number was " + str(number))
f = open("statistics.txt", "a")
f.write =(player_name) (max_guesses)
f.close()
f = open("statistics.txt", "r")
print(f.read())
Maybe add befor you loop the variable won = False
And in the loop
if guess == number:
won = True
break
After the loop if the player don't find the nulber won will be false.
In the oter case it will be True
For saving
f.write( str(won) ) # convert to string
I am basically getting information from the user, have the input placed in a list and ask them for the account number. I also have them enter their name and balance inserted into two other list. I want it to only print their specific number,name, and balance based on what account number they have entered using a loop instead of an if and elif
count = 0
while count != 4:
name = input("Enter your name: ")
customers.append(name)
num = int(input("Enter account number: "))
acctnum.append(num)
bal = float(input("Enter Current Balance:$ "))
print()
balance.append(bal)
count = count + 1
personal = int(input("Enter account number: "))
withdraw = int(input("Enter amount to be withdrawn: "))
if personal in acctnum:
if (acctnum.index(personal)) == 0:
print()
print("\nCustomer name: ", customers[0])
print("Account Number: ",acctnum[0])
print("Balance: ", balance[0])
newbal = balance[0]
print()
elif (acctnum.index(personal)) == 1:
print("\nCustomer name: ", customers[1])
print("Account Number: ",acctnum[1])
print("Balance: ", balance[1])
newbal = balance[1]
print()
elif (acctnum.index(personal)) == 2:
print("\nCustomer name: ", customers[2])
print("Account Number: ",acctnum[2])
print("Balance: ", balance[2])
newbal = balance[2]
print()
elif (acctnum.index(personal)) == 3:
print("\nCustomer name: ", customers[3])
print("Account Number: ",acctnum[3])
print("Balance: ", balance[3])
newbal = balance[3]
print()
elif (acctnum.index(personal)) == 4:
print("\nCustomer name: ", customers[4])
print("Account Number: ",acctnum[4])
print("Balance: ", balance[4])
newbal = balance[4]
print()
Something like this loop structure would reduce the necessary elif statements:
if personal in acctnum:
for i in range(4):
if (acctnum.index(personal)) == i:
print()
print("\nCustomer name: ", customers[i])
print("Account Number: ",acctnum[i])
print("Balance: ", balance[i])
newbal = balance[i]
print()
You could always replace the 4 in for i in range(4) with a variable that tracks the number of accounts.
So far the user is supposed to enter their name account number and balance which gets put into list. then I ask for them to input their account number and im supposed to print out their specific number from the list instead of the whole list but cant get it to work.
customers = list()
acctnum = list()
balance= list()
count = 0
while count != 2:
name = input("Enter your name: ")
customers.append(name)
num = int(input("Enter account number: "))
acctnum.append(num)
bal = input("Enter Current Balance:$ ")
print()
balance.append(bal)
count = count + 1
print(customers)
print(acctnum)
print(balance)
personal = int(input("Enter account number: "))
print(personal)
if personal in acctnum:
print(acctnum)
I find dictionaries are useful in applications like this:
accounts = {}
for x in range(2):
name = input("Enter your name: ")
num = int(input("Enter account number: "))
bal = input("Enter Current Balance: $")
accounts[num] = {"name": name, "balance": bal}
print()
for k, v in accounts.items():
print(v["name"] + "'s account " + str(k) + " has $" + v["balance"])
personal = int(input("Enter account number: "))
if personal in accounts:
print("Hello, " + accounts[personal]["name"] + " you have $" + accounts[personal]["balance"])
The data right now is stored in independent lists. You would have to implement using an associative data type such as dictionaries (that are implemented in Python).
I am currently learning Python and I am making a tennis coach program. On the option 3 where you can update it is not working as it says nameUnder is not defined in the else statement. Please help as I really don't understand why its not working. I have also tries it without the split but that to doesn't work
import os, sys
print("Please select an option:")
print("[1] Add a student")
print("[2] Read a students data")
print("[3] Update a students data")
print("[4] Delete a students data")
menuSelect = int(input("Make your number selection: "))
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if menuSelect == 1:
amountDone=0
amounttodo=int(input("Enter the number of contestants you would like to add: "))
while amounttodo>amountDone:
ageOne=int(input("Enter the age of the contestant: "))
if ageOne <= 11:
underFile=open("Under11s.txt","a")
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
underFile.write("\n"+str(nameUnder) + " | " + str(genderUnder) + " | " + str(posUnder))
underFile.close()
amountDone=amountDone+1
elif ageOne >= 12:
overFile=open("Over11s.txt","a")
nameOver=input("Enter the first name of the student: ")
genderOver=input("Enter the gender of the student: ")
posOver=int(input("Input the last position of the student: "))
overFile.write("\n"+str(nameOver) + " | " + str(genderOver) + " | " + str(posOver))
overFile.close()
amountDone=amountDone+1
else:
print("Invalid, Please enter a number")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 2:
print("Enter the file you would like to open.")
print("1) Under 11's")
print("2) Over 11's")
fileToOpen=int(input("Enter the number of your selection: "))
if fileToOpen == 1:
f = open("Under11s.txt", "r")
file_contents = f.read()
print(file_contents)
elif fileToOpen == 2:
f = open("Over11s.txt", "r")
file_contents = f.read()
print(file_contents)
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
elif menuSelect == 3:
studentName = input("Enter the student name you are looking for:")
file = open("Under11s.txt","r")
found=False
for line in file:
details = line.split(",")
writefile = open("Under11supdated.txt","a")
details = line.split(",")
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")
posUnder=int(input("Input the last position of the student: "))
file.write("\n"+str(nameUnder)[0] + " | " + str(genderUnder)[1] + " | " + str(posUnder)[2])
else:
file.write("\n"+nameUnder[0] + " | " + genderUnder[1] + " | " + posUnder[2])
file.close()
file.close()
os.remove("Under11s.txt")
os.rename("Under11supdated.txt","Under11s.txt")
if found==True:
print("Details updated")
else:
print("That student cannot be found in the file, no changes made")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
else:
print("Sorry, this option is not available yet!")
#/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
nameUnder only gets defined if this statement is true if details[0] == studentName:
Not a 100% of your logic here, but make sure to set nameUnder= "" before the if statement so the variable is declared and can be used in your else clause.
I would recommend you to structure your code with functions for the each options etc., will make it easier to read and possible reuse some of the code.
Partly updated code:
writefile = open("Under11supdated.txt","a")
details = line.split(",")
nameUnder = ""
if details[0] == studentName:
found=True
nameUnder=input("Enter the first name of the student: ")
genderUnder=input("Enter the gender of the student: ")